Full width home advertisement

OpenCV

HTML

Post Page Advertisement [Top]

    In this post I am explaining the implementation algorithm for correcting lens distortion using OpenCV. The actual post for this algorithm can find here A simple algorithm for correcting lens distortion . For more information about the algorithm read the original post.

C++ Code


char window_name[30] = "Lens Distortion Correction";
int strengthVal =0;
int zoomVal =1;
Mat srcOriginal;
void correctLensDistortion(){

      Mat src = srcOriginal.clone();
      double imageWidth =  src.cols;
      double imageHeight =  src.rows;
      Mat dst(imageHeight,imageWidth,CV_8UC3,Scalar::all(0));
      double strength =(double) strengthVal/10;
      double zoom = (double) zoomVal/10;
      if(zoom<1)
          zoom = 1;



      double halfWidth = src.cols / 2;
      double halfHeight = src.rows / 2;
      if(strength ==0)
         strength = 0.00001;

      double correctionRadius = sqrt(imageWidth * imageWidth + imageHeight *imageHeight) / strength;
      for(double y=0; y < dst.rows; y++){
       for(double x=0; x < dst.cols; x++){
           double newX = x - halfWidth;
           double newY = y - halfHeight;
           double distance = sqrt(newX *newX + newY *newY);
           double r = distance / correctionRadius;
           double theta;
           if (r == 0)
              theta = 1.0;
           else
              theta = atan(r) / r;

          double sourceX = halfWidth + theta * newX * zoom;
          double sourceY = halfHeight + theta * newY * zoom;
          if(sourceX >= 0 && sourceY >= 0 && sourceX < src.cols&&sourceY < src.rows)
            dst.at < Vec3b > (Point(x,y)) = src.at < Vec3b > (Point(sourceX,sourceY));

       }
      }

      imshow(window_name,src);
      imshow("dst",dst);

}



static void on_trackbar_changed(int, void*){
   correctLensDistortion();
}



int main()
{
    srcOriginal = imread("src.jpg", IMREAD_COLOR);
    namedWindow(window_name, CV_WINDOW_AUTOSIZE); // Create Window
    createTrackbar( "Strength", window_name, &strengthVal, 100, on_trackbar_changed );
    createTrackbar( "Zoom", window_name, &zoomVal, 100,on_trackbar_changed );
    setTrackbarPos("Strength", window_name,5);
    setTrackbarPos("Zoom", window_name,1);
    correctLensDistortion();
    while(true) {
      int  c = waitKey( 20 );
      if( (char)c == 27 )
          break;
     }
     return 0;
}

Result

Source Image


Distortion corrected result


No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib