title: How to convert Matrix to a type Mat?
body: <p>I am using EmguCV to do simple image processing. I want to remove small contours from my thresholded image so I used <strong>connectedcomponentswithstats</strong>. Below is my code where I convert any pixel smaller than the minimum size into black - essentially deleting it. The reason I want to do this is to be able to use it in the latter part since it is not compatible with other types.</p>
  
  <pre><code>public Mat Filtered(Mat in_img, string currentDir)
  {
      Mat gray_res = new Mat();
      Mat labels = new Mat();
      Mat stats = new Mat();
      Mat centroids = new Mat();
  
      CvInvoke.CvtColor(in_img, gray_res, ColorConversion.Bgr2Gray);
  
      var nlabels = CvInvoke.ConnectedComponentsWithStats(gray_res, labels, stats, centroids, LineType.EightConnected);
  
      int min_size = 250;
  
      int[] sizes = new int[nlabels];
  
      for (int s = 1; s &lt; nlabels; s++)
      {
          sizes[s] = BitConverter.ToInt32(stats.GetData(s, (int)ConnectedComponentsTypes.Area), 0);
      }
  
      Matrix&lt;double&gt; fltr_img = new Matrix&lt;double&gt;(labels.Rows, labels.Cols);
      fltr_img.SetValue(0);
  
      for (int i = 1; i &lt; nlabels; i++)
      {
          int j = BitConverter.ToInt32(stats.GetData(i, (int)ConnectedComponentsTypes.Left), 0); //left most
          int w = BitConverter.ToInt32(stats.GetData(i, (int)ConnectedComponentsTypes.Width), 0); //run width
          int k = BitConverter.ToInt32(stats.GetData(i, (int)ConnectedComponentsTypes.Top), 0); //top most
          int h = BitConverter.ToInt32(stats.GetData(i, (int)ConnectedComponentsTypes.Height), 0); //run height
  
          if (sizes[i] &lt; min_size)
          {
              for (int a = k; a &lt; k + h; a++)
              {
                  for (int b = j; b &lt; j + w; b++)
                  {
                      fltr_img.Data[a, b] = 255;
                  }
              }
          }
      }
  
      //Covnert 2D Matrix to Image
      CvInvoke.Imwrite(currentDir + "filter.jpg", fltr_img);
  
      Mat subtrahend = CvInvoke.Imread(currentDir + "filter.jpg");
  
      Mat fnl_img = new Mat();
  
      CvInvoke.Subtract(in_img, subtrahend, fnl_img);
  
      return fnl_img;
  }
  </code></pre>
  
  <p>What I did, in the end, is a little dirty trick to convert the mask into a compatible type <strong>Mat</strong> which is the original image. With this code, I am getting my result but I am still bothered by it.</p>