title: Change RGB to GrayScale in c++
body: <p>I am trying to convert RGB image to gray scale using average method. But the output that is get is different from the desired output. I'm taking the image and getting the rgb values. I perform average operation and store the averaged and another array of same size of the image. Finally i'm converting the array to Mat and displaying the image. </p>
  
  <p>Input image:</p>
  
  <p><img src="https://i.stack.imgur.com/gRE66.jpg" alt="Input image"> </p>
  
  <p>Desired output:</p>
  
  <p><img src="https://i.stack.imgur.com/veA3g.jpg" alt="desired output"> </p>
  
  <p>My output:</p>
  
  <p><img src="https://i.stack.imgur.com/eE5Rw.jpg" alt="my output"></p>
  
  <pre><code>int main()
  {
   Mat image;
  
   image =imread("&lt;image_path&gt;");
  
   int rows=image.rows;
   int cols=image.cols;
  
   int myArray[rows][cols];
  
  
   for (int i = 0; i &lt; rows; i++) {
     for (int j = 0; j &lt; cols; j++) {
       myArray[i][j] = 0;
     }
   }
  
   uint8_t* pixelPtr = (uint8_t*)image.data;
  
   int cn = image.channels();
  
   Scalar_&lt;uint8_t&gt; bgrPixel;
  
   for(int i = 0; i &lt; rows; i++)
  
   {
       for(int j = 0; j &lt; cols; j++)
  
       {
           bgrPixel.val[0] = pixelPtr[i*image.cols*cn + j*cn + 0]; // B
  
           bgrPixel.val[1] = pixelPtr[i*image.cols*cn + j*cn + 1]; // G
  
           bgrPixel.val[2] = pixelPtr[i*image.cols*cn + j*cn + 2]; // R
  
           int average = (bgrPixel.val[0]+bgrPixel.val[1]+bgrPixel.val[2])/3;
  
           myArray[i][j]=average;
  
  
       }
  
   }
  
   Mat averaged_image(Size(rows, cols), CV_8UC3, myArray, Mat::AUTO_STEP);
  
   imwrite("&lt;path to save the image&gt;",averaged_image);
  
   imshow("averaged_image",averaged_image);
  
   waitKey(0);
  
   return 0;
  }
  </code></pre>