title: Opencv: EM algorithm training slowly
body: <p>I am trying to use opencv EM algorithm library. </p>
  
  <p>I tried some example about EM algorithm such like <a href="http://subokita.com/2014/03/24/image-segmentation-using-opencvs-expectation-maximization/" rel="nofollow noreferrer">this</a> and <a href="https://stackoverflow.com/questions/12490256/opencv-color-extraction-based-on-gaussian-mixture-model">this</a> first, but I got the same problem in these code. It take me lots of time in EM training step.</p>
  
  <p>This is my testing code for image segmentation from <a href="http://subokita.com/2014/03/24/image-segmentation-using-opencvs-expectation-maximization/" rel="nofollow noreferrer">this website</a>: </p>
  
  <pre><code>#include &lt;opencv2/opencv.hpp&gt;
  #include &lt;opencv2/legacy/legacy.hpp&gt;
  using namespace std;
  using namespace cv;
  Mat asSamplesVectors(Mat&amp; 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 &lt;&lt; "Starting EM training" &lt;&lt; endl;
      EM em(no_of_clusters);
      em.train(samples);
      cout &lt;&lt; "Finished training EM" &lt;&lt; endl;
  
      vector&lt;Mat&gt; segmented;
      for (int i = 0; i &lt; no_of_clusters; i++)
          segmented.push_back(Mat::zeros(image.rows, image.cols, CV_8UC3));
  
      int index = 0;
      for (int y = 0; y &lt; image.rows; y++) {
          for (int x = 0; x &lt; image.cols; x++) {
              int result = em.predict(samples.row(index++))[1];
              segmented[result].at&lt;Point3i&gt;(y, x, 0) = image.at&lt;Point3i&gt;(y, x, 0);
          }
      }
      imshow("result", samples);
      return(0);
  }
  
  Mat asSamplesVectors(Mat&amp; 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 &lt; img.rows; y++) {
          Vec3f* row = float_img.ptr&lt;Vec3f&gt;(y);
          for (int x = 0; x &lt; img.cols; x++)
              samples.at&lt;Vec3f&gt;(index++, 0) = row[x];
      }
      return samples;
  }
  </code></pre>
  
  <p>I test in VS2013, opencv 2.4.9 and opencv 2.4.11.</p>
  
  <p>This is my testing <a href="https://i.stack.imgur.com/QSI4E.jpg" rel="nofollow noreferrer">image</a>.</p>
  
  <p>In this code, it show me the error <a href="https://i.imgur.com/t8TUzGP.png" rel="nofollow noreferrer">message</a>.</p>
  
  <p>The error step is <code>segmented[result].at&lt;Point3i&gt;(y, x, 0) = image.at&lt;Point3i&gt;(y, x, 0);</code></p>
  
  <p><strong>My first question is:</strong> why the EM training so slowly. Is it normally?</p>
  
  <p><strong>Second question is:</strong> what's wrong with my code error and is there any better example to let me know the usage of EM?</p>