title: Applying a kernel with OpenCV in C++
body: <p>If I apply a Sobel filter to an image in Python using <code>scipy.ndimage.filters.convole</code> I get meaningful results, for example, for this simple input image <code>img</code></p>
  
  <pre><code>0 255 0
  0 255 0
  0 255 0
  </code></pre>
  
  <p>the convolution </p>
  
  <pre><code>dimage.filters.convolve(img, Kx)
  </code></pre>
  
  <p>with <code>Kx</code></p>
  
  <pre><code>-1 0 1
  -2 0 2
  -1 0 1
  </code></pre>
  
  <p>returns a meaningful gradient in x-direction:</p>
  
  <pre><code>-1020 0 1020
  -1020 0 1020
  -1020 0 1020
  </code></pre>
  
  <p>I don't know how to get a equivalent result using openCV2 in C++ though. When I define the input image by</p>
  
  <pre><code>int image_data[9] = {0, 255, 0, 0, 255, 0, 0, 255, 0};
  cv::Mat image = cv::Mat(3, 3, CV_32F, image_data);
  </code></pre>
  
  <p>and apply the kernel by</p>
  
  <pre><code>cv::Mat gradientx; 
  double sobelx_data[9] = {-1, 0, 1, -2, 0, 2, -1, 0, 1};
  cv::Mat sobelx = cv::Mat(3, 3, CV_32F, sobelx_data);
  cv::filter2D(image, gradientx, -1, sobelx);
  </code></pre>
  
  <p>I get the following result from</p>
  
  <pre><code>for(int row=0; row&lt;gradientx.rows; row++) {
    for(int col=0; col&lt;gradientx.cols; col++) {
    std::cout &lt;&lt; gradientx.at&lt;int&gt;(row,col) &lt;&lt; std::endl;
    }
  }
  </code></pre>
  
  <p>it returns the following image </p>
  
  <pre><code>478 -2147482660 478
  478 -2147482660 478
  478 -2147482660 478
  </code></pre>
  
  <p>There seems to be an overflow problem, but I don't know why. Trying to get values from <code>gradientx.at&lt;double&gt;(row,col)</code> produces </p>
  
  <pre><code>-1.68911e-311 8.10602e-312 8.11663e-312
  -1.68911e-311 8.10602e-312 8.11663e-312
  -1.68911e-311 2.122e-314 8.54412e-72
  </code></pre>
  
  <p>Can someone tell me why this is? Isn't <code>filter2D</code> supposed to do a 2D convolution on the image, and why do I get weird values when addressing the output pixels with <code>&lt;double&gt;</code>? Thank you.</p>