title: OpenCV C++. Quickly compute confusion matrix
body: <p>What is the preferred way to compute a confusion matrix with OpenCV and C++?</p>
  
  <p>Starting from:</p>
  
  <pre><code>int TP = 0,FP = 0,FN = 0,TN = 0;
  cv::Mat truth(60,60, CV_8UC1);
  cv::Mat detections(60,60, CV_8UC1);
  
  this-&gt;loadResults(truth, detections); // loadResults(cv::Mat&amp; t, cv::Mat&amp; d);
  </code></pre>
  
  <p>I tried a few different options like:</p>
  
  <ol>
  <li><p>Direct Calls:</p>
  
  <pre><code>for(int r = 0; r &lt; detections.rows; ++r)
  for(int c = 0; c &lt; detections.cols; ++c)
  {
      int d,t;
      d = detection.at&lt;unsigned char&gt;(r,c);
      t = truth.at&lt;unsigned char&gt;(r,c);
      if(d&amp;&amp;t)    ++TP;
      if(d&amp;&amp;!t)   ++FP;
      if(!d&amp;&amp;t)   ++FN;
      if(!d&amp;&amp;!t)  ++TN;
  }
  </code></pre></li>
  <li><p>RAM heavy matrix logic:</p>
  
  <pre><code>{
      cv::Mat truePos = detection.mul(truth);
      TP = cv::countNonZero(truePos)
  }
  {
      cv::Mat falsePos = detection.mul(~truth);
      FP = cv::countNonZero(falsePos )
  }
  {
      cv::Mat falseNeg = truth.mul(~detection);
      FN = cv::countNonZero(falseNeg )
  }
  {
      cv::Mat trueNeg = (~truth).mul(~detection);
      TN = cv::countNonZero(trueNeg )
  }
  </code></pre></li>
  <li><p>forEach:</p>
  
  <pre><code>auto lambda = [&amp;, truth,TP,FP,FN,TN](unsigned char d, const int pos[]){
      cv::Point2i pt(pos[1], pos[0]);
      char t = truth.at&lt;unsigned char&gt;(pt);
      if(d&amp;&amp;t)    ++TP;
      if(d&amp;&amp;!t)   ++FP;
      if(!d&amp;&amp;t)   ++FN;
      if(!d&amp;&amp;!t)  ++TN;
  };
  detection.forEach(lambda);
  </code></pre></li>
  </ol>
  
  <p>But is there a standard way of doing it? I might have missed a simple function in OpenCV docs.</p>
  
  <p>p.s. I used VS2010 x64;</p>