title: C++: OpenCV: fast pixel iteration
body: <p>I'm trying to get BGR values from a streaming webcam image. I'm getting a memory access violation because I'm not using the pointer correctly in the nested for loop but I don't know what the syntax should be. I can't find documentation that is specific enough to the seemingly basic task I'm trying to do. </p>
  
  <p>In addition to solving he memory access violation, I want to also be able to edit each pixel on the fly without having to do a deep copy but don't know what he syntax should be for that also.</p>
  
  <p>This is the code I have so far:</p>
  
  <pre><code>int main(int argc, char** argv)
  {
  
      int c;
      Mat img;
      VideoCapture capture(0);
      namedWindow("mainWin", CV_WINDOW_AUTOSIZE);
      bool readOk = true;
  
      while (capture.isOpened()) {
  
          readOk = capture.read(img);
  
          // make sure we grabbed the frame successfully 
          if (!readOk) {
              std::cout &lt;&lt; "No frame" &lt;&lt; std::endl;
              break;
          }
  
          int nChannels = img.channels();
          int nRows = img.rows;
          int nCols = img.cols * nChannels;
  
          if (img.isContinuous())
          {
              nCols *= nRows;
              nRows = 1;
          }
  
          int i, j;
          uchar r, g, b;
          for (i = 0; i &lt; nRows; ++i)
          {
              for (j = 0; j &lt; nCols; ++j)
              {
                  r = img.ptr&lt;uchar&gt;(i)[nChannels*j + 2];
                  g = img.ptr&lt;uchar&gt;(i)[nChannels*j + 1];
                  b = img.ptr&lt;uchar&gt;(i)[nChannels*j + 0];
              }
          }
  
          if (!img.empty()) imshow("mainWin", img);
          c = waitKey(10);
          if (c == 27)
              break;
      }
  }
  </code></pre>