Correct barrel distortion in OpenCV manually, without chessboard image

Michael Hecht picture Michael Hecht · Oct 28, 2014 · Viewed 14.9k times · Source

I get images from a camera where it is not possible to take a chessboard picture and calculate the correction matrix using OpenCV. Up to now I corrected the images using imagemagick convert with the option '-distort Barrel "0.0 0.0 -0.035 1.1"' where I got the parameters with trial and error.

Now I want to do this inside OpenCV but all I find in the web is the automatic correction using the chessboard image. Is there any chance to apply some simple manual trial and error lens distortion correction as I did with imagemagick?

Answer

Michael Hecht picture Michael Hecht · Oct 28, 2014

Ok, I think I got it. In the matrices cam1, cam2 the image centers were missing (see documentation). I added it and changed the focal length to avoid a too strong change of image size. Here is the code:

  import numpy as np
  import cv2

  src    = cv2.imread("distortedImage.jpg")
  width  = src.shape[1]
  height = src.shape[0]

  distCoeff = np.zeros((4,1),np.float64)

  # TODO: add your coefficients here!
  k1 = -1.0e-5; # negative to remove barrel distortion
  k2 = 0.0;
  p1 = 0.0;
  p2 = 0.0;

  distCoeff[0,0] = k1;
  distCoeff[1,0] = k2;
  distCoeff[2,0] = p1;
  distCoeff[3,0] = p2;

  # assume unit matrix for camera
  cam = np.eye(3,dtype=np.float32)

  cam[0,2] = width/2.0  # define center x
  cam[1,2] = height/2.0 # define center y
  cam[0,0] = 10.        # define focal length x
  cam[1,1] = 10.        # define focal length y

  # here the undistortion will be computed
  dst = cv2.undistort(src,cam,distCoeff)

  cv2.imshow('dst',dst)
  cv2.waitKey(0)
  cv2.destroyAllWindows()

Thank you very much for your assistence.