title: How to process a JPEG binary data in OpenCV?
body: <p>I am trying to process a JPEG Binary data in OpenCV. When I do that I get <strong>Segmentation fault (core dumped)</strong>.</p>
  
  <p>I read JPEG file through <code>fread</code> command and stored in a buffer.</p>
  
  <p>After reading, I copied the buffer data to a <code>Mat</code> variable, 
  When I tried to do grayscale conversion on copied data using <code>cvtColor</code> OpenCV function. I get Segmentation Fault. </p>
  
  <pre><code>int main( int argc, char** argv )
  {
  
      Mat threshold_output;
      Mat gray_image;
  
      unsigned char *pre_image;
      FILE *read_image;
      FILE *write_image;
      int filesize;
      size_t data, write;
  
      read_image = fopen(argv[1] , "rb"); //Read Jpeg as Binary
      write_image = fopen("output11.jpg", "wb"); //Write JPEG
  
      if(read_image == NULL)
      {
          printf("Image Not Found\r\n");
      }
      fseek(read_image, 0, SEEK_END);
      int fileLen = ftell(read_image);
      fseek(read_image, 0, SEEK_SET);
  
      pre_image = (unsigned char *)malloc(fileLen);
      data = fread(pre_image, 1, fileLen, read_image);
      write = fwrite(pre_image, 1, fileLen, write_image);
  
      // Printed and verify the values
      printf("File Size %d\r\n", fileLen);
      printf("Read bytes %zu\r\n", data);
      printf("Write bytes %zu\r\n", data);
  
      fclose(read_image);
      fclose(write_image);
  
      /* Copy the Jpeg Binary buffer to a MAt Variable*/  
      cv::Mat image(Size(640, 480), CV_8UC3, pre_image); //Seg Fault comes here
      /* Convert Grayscale */
      cvtColor( image, gray_image, CV_BGR2GRAY);
      /* Threshold conversion */
      threshold( gray_image, threshold_output, 80, 255, THRESH_BINARY );
  
      namedWindow( "Thresholded", CV_WINDOW_AUTOSIZE );
      imshow( "Thresholded", image );
  
      waitKey(0);
      return 0;
  }
  </code></pre>
  
  <p>I have attached the code for reference. I have verified that both <code>fread</code> and <code>fwrite</code> works properly. 
  But when I do the <code>cvtColor</code> only I got error.</p>