title: distortion correction with gpu shader bug
body: <p>So I have a camera with a wide angle lens. I know the distortion coefficients, the focal length, the optical center. I want to undistort the image I get from this camera. I used OpenCV for the first try (cv::undistort), which worked well, but was way too slow.</p>
  
  <p>Now I want to do this on the gpu. There is a shader doing exactly this documented in <a href="http://willsteptoe.com/post/67401705548/ar-rift-aligning-tracking-and-video-spaces-part-5" rel="nofollow">http://willsteptoe.com/post/67401705548/ar-rift-aligning-tracking-and-video-spaces-part-5</a> </p>
  
  <p>the formulas can be seen here:
  <a href="http://en.wikipedia.org/wiki/Distortion_%28optics%29#Software_correction" rel="nofollow">http://en.wikipedia.org/wiki/Distortion_%28optics%29#Software_correction</a></p>
  
  <p>So I went and implemented my own version as a glsl shader. I am sending a quad with texture coordinates on the corners between 0..1. 
  I assume the texture coordinates that arrive are the coordinates of the undistorted image. I calculate the coordinates for the distorted point corresponding to my texture coordinates. Then I sample the distorted image texture. </p>
  
  <p>With this shader <em>nothing</em> in the final image changes. The problem I identified through a cpu implementation is, the coefficient term is very close to zero. The numbers get smaller and smaller through radius squaring etc.. So I have a scaling problem - I can't figure it out what to do differently! I tried everything... I guess it is something quite obvious, since this kind of process seems to work for a lot of people.</p>
  
  <p>I left out the tangential distortion correction for simplicity.</p>
  
  <pre><code>#version 330 core
  
  in vec2 UV;
  
  out vec4 color;
  
  uniform sampler2D textureSampler;
  
  void main()
  {   
      vec2 focalLength = vec2(438.568f, 437.699f);
      vec2 opticalCenter = vec2(667.724f, 500.059f);
      vec4 distortionCoefficients = vec4(-0.035109f, -0.002393f, 0.000335f, -0.000449f);
  
      const vec2 imageSize = vec2(1280.f, 960.f);
  
      vec2 opticalCenterUV = opticalCenter / imageSize;
  
      vec2 shiftedUVCoordinates = (UV - opticalCenterUV);
  
      vec2 lensCoordinates = shiftedUVCoordinates / focalLength;
  
      float radiusSquared = sqrt(dot(lensCoordinates, lensCoordinates));
      float radiusQuadrupled = radiusSquared * radiusSquared;
  
      float coefficientTerm = distortionCoefficients.x * radiusSquared + distortionCoefficients.y * radiusQuadrupled;
  
      vec2 distortedUV = ((lensCoordinates + lensCoordinates * (coefficientTerm))) * focalLength;
  
      vec2 resultUV = (distortedUV + opticalCenterUV);
  
      color = texture2D(textureSampler, resultUV);
  }
  </code></pre>