Skip to content

Commit 24c2c1c

Browse files
Merge pull request #497 from kaustubh-sadekar/master
Added files for lens distortion post.
2 parents 7935c24 + 303502a commit 24c2c1c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+479
-8
lines changed

CameraCalibration/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@ MACRO(add_example name)
1414
ENDMACRO()
1515

1616
add_example(cameraCalibration)
17+
add_example(cameraCalibrationWithUndistortion)

CameraCalibration/README.md

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,32 @@ Calibrate your camera using OpenCV.
44

55
## Using the C++ code
66
### Compilation
7-
To compile the `cameraCalibration.cpp` code, use the following:
7+
To compile the `cameraCalibration.cpp` and `cameraCalibrationWithUndistortion.cpp` code files, use the following:
88
```shell
99
mkdir build
1010
cd build
1111
cmake ..
1212
cmake --build . --config Release
1313
```
14-
### Usage
15-
Refer to the following to use the compiled file:
16-
`./build/cameraCalibration`
14+
## Usage
1715

18-
## Using the python code
19-
### Usage
20-
Refer to the following to use the `cameraCalibration.py` file:
21-
`python3 cameraCalibration.py`
16+
### Using the C++ code
2217

18+
Refer to the following to use the compiled files:
19+
20+
```shell
21+
./build/cameraCalibration
22+
./build/cameraCalibrationWithUndistortion
23+
```
24+
25+
### Using the python code
26+
27+
Refer to the following to use the `cameraCalibration.py` and `cameraCalibrationWithUndistortion.py` files respectively:
28+
29+
```shell
30+
python3 cameraCalibration.py
31+
python3 cameraCalibrationWithUndistortion.py
32+
```
2333

2434
# AI Courses by OpenCV
2535

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
#include <opencv2/opencv.hpp>
2+
#include <opencv2/calib3d/calib3d.hpp>
3+
#include <opencv2/highgui/highgui.hpp>
4+
#include <opencv2/imgproc/imgproc.hpp>
5+
#include <stdio.h>
6+
#include <iostream>
7+
8+
// Defining the dimensions of checkerboard
9+
int CHECKERBOARD[2]{6,9};
10+
11+
int main()
12+
{
13+
// Creating vector to store vectors of 3D points for each checkerboard image
14+
std::vector<std::vector<cv::Point3f> > objpoints;
15+
16+
// Creating vector to store vectors of 2D points for each checkerboard image
17+
std::vector<std::vector<cv::Point2f> > imgpoints;
18+
19+
// Defining the world coordinates for 3D points
20+
std::vector<cv::Point3f> objp;
21+
for(int i{0}; i<CHECKERBOARD[1]; i++)
22+
{
23+
for(int j{0}; j<CHECKERBOARD[0]; j++)
24+
objp.push_back(cv::Point3f(j,i,0));
25+
}
26+
27+
28+
// Extracting path of individual image stored in a given directory
29+
std::vector<cv::String> images;
30+
// Path of the folder containing checkerboard images
31+
std::string path = "./images/*.jpg";
32+
33+
cv::glob(path, images);
34+
35+
cv::Mat frame, gray;
36+
// vector to store the pixel coordinates of detected checker board corners
37+
std::vector<cv::Point2f> corner_pts;
38+
bool success;
39+
40+
// Looping over all the images in the directory
41+
for(int i{0}; i<images.size(); i++)
42+
{
43+
frame = cv::imread(images[i]);
44+
cv::cvtColor(frame,gray,cv::COLOR_BGR2GRAY);
45+
46+
// Finding checker board corners
47+
// If desired number of corners are found in the image then success = true
48+
success = cv::findChessboardCorners(gray,cv::Size(CHECKERBOARD[0],CHECKERBOARD[1]), corner_pts, cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_FAST_CHECK | cv::CALIB_CB_NORMALIZE_IMAGE);
49+
50+
/*
51+
* If desired number of corner are detected,
52+
* we refine the pixel coordinates and display
53+
* them on the images of checker board
54+
*/
55+
if(success)
56+
{
57+
cv::TermCriteria criteria(cv::TermCriteria::EPS | cv::TermCriteria::MAX_ITER, 30, 0.001);
58+
59+
// refining pixel coordinates for given 2d points.
60+
cv::cornerSubPix(gray,corner_pts,cv::Size(11,11), cv::Size(-1,-1),criteria);
61+
62+
// Displaying the detected corner points on the checker board
63+
cv::drawChessboardCorners(frame, cv::Size(CHECKERBOARD[0],CHECKERBOARD[1]), corner_pts,success);
64+
65+
objpoints.push_back(objp);
66+
imgpoints.push_back(corner_pts);
67+
}
68+
69+
cv::imshow("Image",frame);
70+
cv::waitKey(0);
71+
}
72+
73+
cv::destroyAllWindows();
74+
75+
cv::Mat cameraMatrix,distCoeffs,R,T;
76+
77+
/*
78+
* Performing camera calibration by
79+
* passing the value of known 3D points (objpoints)
80+
* and corresponding pixel coordinates of the
81+
* detected corners (imgpoints)
82+
*/
83+
cv::calibrateCamera(objpoints, imgpoints,cv::Size(gray.rows,gray.cols),cameraMatrix,distCoeffs,R,T);
84+
85+
std::cout << "cameraMatrix : " << cameraMatrix << std::endl;
86+
std::cout << "distCoeffs : " << distCoeffs << std::endl;
87+
std::cout << "Rotation vector : " << R << std::endl;
88+
std::cout << "Translation vector : " << T << std::endl;
89+
90+
91+
// Trying to undistort the image using the camera parameters obtained from calibration
92+
93+
cv::Mat image;
94+
image = cv::imread(images[0]);
95+
cv::Mat dst, map1, map2,new_camera_matrix;
96+
cv::Size imageSize(cv::Size(image.cols,image.rows));
97+
98+
// Refining the camera matrix using parameters obtained by calibration
99+
new_camera_matrix = cv::getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0);
100+
101+
// Method 1 to undistort the image
102+
cv::undistort( frame, dst, new_camera_matrix, distCoeffs, new_camera_matrix );
103+
104+
// Method 2 to undistort the image
105+
cv::initUndistortRectifyMap(cameraMatrix, distCoeffs, cv::Mat(),cv::getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0),imageSize, CV_16SC2, map1, map2);
106+
107+
cv::remap(frame, dst, map1, map2, cv::INTER_LINEAR);
108+
109+
//Displaying the undistorted image
110+
cv::imshow("undistorted image",dst);
111+
cv::waitKey(0);
112+
113+
return 0;
114+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#!/usr/bin/env python
2+
3+
import cv2
4+
import numpy as np
5+
import os
6+
import glob
7+
8+
# Defining the dimensions of checkerboard
9+
CHECKERBOARD = (6,9)
10+
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
11+
12+
# Creating vector to store vectors of 3D points for each checkerboard image
13+
objpoints = []
14+
# Creating vector to store vectors of 2D points for each checkerboard image
15+
imgpoints = []
16+
17+
18+
# Defining the world coordinates for 3D points
19+
objp = np.zeros((1, CHECKERBOARD[0]*CHECKERBOARD[1], 3), np.float32)
20+
objp[0,:,:2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2)
21+
prev_img_shape = None
22+
23+
# Extracting path of individual image stored in a given directory
24+
images = glob.glob('./images/*.jpg')
25+
for fname in images:
26+
img = cv2.imread(fname)
27+
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
28+
# Find the chess board corners
29+
# If desired number of corners are found in the image then ret = true
30+
ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD, cv2.CALIB_CB_ADAPTIVE_THRESH+
31+
cv2.CALIB_CB_FAST_CHECK+cv2.CALIB_CB_NORMALIZE_IMAGE)
32+
33+
"""
34+
If desired number of corner are detected,
35+
we refine the pixel coordinates and display
36+
them on the images of checker board
37+
"""
38+
if ret == True:
39+
objpoints.append(objp)
40+
# refining pixel coordinates for given 2d points.
41+
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
42+
43+
imgpoints.append(corners2)
44+
45+
# Draw and display the corners
46+
img = cv2.drawChessboardCorners(img, CHECKERBOARD, corners2,ret)
47+
48+
cv2.imshow('img',img)
49+
cv2.waitKey(0)
50+
51+
cv2.destroyAllWindows()
52+
53+
h,w = img.shape[:2]
54+
55+
"""
56+
Performing camera calibration by
57+
passing the value of known 3D points (objpoints)
58+
and corresponding pixel coordinates of the
59+
detected corners (imgpoints)
60+
"""
61+
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
62+
63+
print("Camera matrix : \n")
64+
print(mtx)
65+
print("dist : \n")
66+
print(dist)
67+
print("rvecs : \n")
68+
print(rvecs)
69+
print("tvecs : \n")
70+
print(tvecs)
71+
72+
# Using the derived camera parameters to undistort the image
73+
74+
img = cv2.imread(images[0])
75+
# Refining the camera matrix using parameters obtained by calibration
76+
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))
77+
78+
# Method 1 to undistort the image
79+
dst = cv2.undistort(img, mtx, dist, None, newcameramtx)
80+
81+
# Method 2 to undistort the image
82+
mapx,mapy=cv2.initUndistortRectifyMap(mtx,dist,None,newcameramtx,(w,h),5)
83+
84+
dst = cv2.remap(img,mapx,mapy,cv2.INTER_LINEAR)
85+
86+
# Displaying the undistorted image
87+
cv2.imshow("undistorted image",dst)
88+
cv2.waitKey(0)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
cmake_minimum_required(VERSION 2.8.12)
2+
3+
set(CMAKE_CXX_STANDARD 14)
4+
5+
PROJECT(cameracalib)
6+
7+
find_package( OpenCV REQUIRED )
8+
9+
include_directories( ${OpenCV_INCLUDE_DIRS})
10+
11+
MACRO(add_example name)
12+
ADD_EXECUTABLE(${name} ${name}.cpp)
13+
TARGET_LINK_LIBRARIES(${name} ${OpenCV_LIBS})
14+
ENDMACRO()
15+
16+
add_example(Undistort)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Understanding Lens Distortion
2+
3+
Understanding lens distortion using OpenCV.
4+
5+
## Using the C++ code
6+
### Compilation
7+
To compile the `Undistort.cpp` code file, use the following:
8+
```shell
9+
mkdir build
10+
cd build
11+
cmake ..
12+
cmake --build . --config Release
13+
```
14+
## Usage
15+
16+
### Using the C++ code
17+
18+
Refer to the following to use the compiled file:
19+
20+
```shell
21+
./build/Undistort
22+
```
23+
24+
### Using the python code
25+
26+
Refer to the following to use the `Undistort.py` file:
27+
28+
```shell
29+
python3 Undistort.py
30+
```
31+
32+
# AI Courses by OpenCV
33+
34+
Want to become an expert in AI? [AI Courses by OpenCV](https://opencv.org/courses/) is a great place to start.
35+
36+
<a href="https://opencv.org/courses/">
37+
<p align="center">
38+
<img src="https://www.learnopencv.com/wp-content/uploads/2020/04/AI-Courses-By-OpenCV-Github.png">
39+
</p>
40+
</a>

0 commit comments

Comments
 (0)