[Windows] [Python] Camera calibration of fisheye lens with OpenCV

Recently, I've been fascinated by the ease of writing Python code, and I've been writing sample programs in Python quite a bit.

So, the subject of the title. I may use a fisheye lens or a super wide-angle lens for my future work, so if I try to make a trial sample, It seems that the Python version does not have the cv :: fisheye I / F that exists in the C ++ version of OpenCV. .. ..

I couldn't give up in various ways, so I took the turn of normal calibration with Python. I tried to calibrate the fisheye lens. (If you can do it with the Python version, there will be no technical problem if you implement it properly with the C ++ version.

Below, YouTube video ↓ https://www.youtube.com/watch?v=WGtZeyfzve4 [[Windows] [Python] Camera calibration of fisheye lens with OpenCV](https://www.youtube.com/watch? v = WGtZeyfzve4)

that? Is it something you can do normally? Confirm the reason. Also, I don't feel like there are many places where my feelings are cut off. Probably a wide angle of about 130 degrees can be secured.

By the way, the camera used is below ↓ https://www.amazon.co.jp/ELP-USB2-0-Ominivison-OV2710-%E5%BA%A6%E3%83%A1%E3%82%AC%E3%83%94%E3%82%AF%E3%82%BB%E3%83%AB%E9%AD%9A%E7%9C%BC%E3%83%AC%E3%83%B3%E3%82%BA/dp/B017R02JLI DSC_0267.JPG

Paste the code below ↓

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
import cv2
import Tkinter
import tkMessageBox

square_side_length = 23.0 #The size of one side of a square in a chess board(mm)
grid_intersection_size = (10, 7) #Number of grids in the chess board

pattern_points = np.zeros( (np.prod(grid_intersection_size), 3), np.float32 )
pattern_points[:,:2] = np.indices(grid_intersection_size).T.reshape(-1, 2)
pattern_points *= square_side_length
object_points = []
image_points = []

root = Tkinter.Tk()
root.withdraw()

video_input = cv2.VideoCapture(1)
if (video_input.isOpened() == False):
    exit()

camera_mat, dist_coef = [], []

if tkMessageBox.askyesno('askyesno','Calibration data(K.csv, d.csv)Do you want to read?'):
    #Reading calibration data
    camera_mat = np.loadtxt('K.csv', delimiter=',')
    dist_coef = np.loadtxt('d.csv', delimiter=',')
    print "K = \n", camera_mat
    print "d = ", dist_coef.ravel()
else:
    #Shooting chess board
    capture_count = 0
    while(True):
        ret, frame = video_input.read()

        #Convert to grayscale image for chessboard detection
        #grayscale_image = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)

        #Detects chess board corners
        #found, corner = cv2.findChessboardCorners(grayscale_image, grid_intersection_size)
        found, corner = cv2.findChessboardCorners(frame, grid_intersection_size)

        if found == True:
            print 'findChessboardCorners : True'

            #Find Chessboard Corners in current OpenCV()Within, cornerSubPix()Is considerable processing being carried out? Confirmation required
            #term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1)
            #cv2.cornerSubPix(grayscale_image, corner, (5,5), (-1,-1), term)
            #cv2.drawChessboardCorners(grayscale_image, grid_intersection_size, corner, found)

            cv2.drawChessboardCorners(frame, grid_intersection_size, corner, found)
        if found == False:
            print 'findChessboardCorners : False'

        cv2.putText(frame, "Enter:Capture Chessboard(" + str(capture_count) + ")", (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0,0,255), 1)
        cv2.putText(frame, "N    :Completes Calibration Photographing", (100, 75), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0,0,255), 1)
        cv2.putText(frame, "ESC  :terminate program", (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0,0,255), 1)
        #cv2.putText(grayscale_image, "Enter:Capture Chessboard(" + str(capture_count) + ")", (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0,0,255), 1)
        #cv2.putText(grayscale_image, "ESC  :Completes Calibration Photographing.", (100, 75), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0,0,255), 1)
        cv2.imshow('original', frame)
        #cv2.imshow('findChessboardCorners', grayscale_image)

        c = cv2.waitKey(50) & 0xFF
        if c == 13 and found == True: # Enter
            #Added chess board corner detection information
            image_points.append(corner)
            object_points.append(pattern_points)
            capture_count += 1
        if c == 110: # N
            if tkMessageBox.askyesno('askyesno','Do you want to finish chessboard shooting and find the internal parameters of the camera?'):
                cv2.destroyAllWindows()
                break
        if c == 27: # ESC
            if tkMessageBox.askyesno('askyesno','Do you want to exit the program?'):
                video_input.release()
                cv2.destroyAllWindows()
                exit()

    if len(image_points) > 0:
        #Calculate camera internal parameters
        print 'calibrateCamera() start'
        rms, K, d, r, t = cv2.calibrateCamera(object_points,image_points,(frame.shape[1],frame.shape[0]),None,None)
        print "RMS = ", rms
        print "K = \n", K
        print "d = ", d.ravel()
        np.savetxt("K.csv", K, delimiter =',',fmt="%0.14f") #Save camera matrix
        np.savetxt("d.csv", d, delimiter =',',fmt="%0.14f") #Preservation of strain coefficient

        camera_mat = K
        dist_coef = d

        #Evaluation by reprojection error
        mean_error = 0
        for i in xrange(len(object_points)):
            image_points2, _ = cv2.projectPoints(object_points[i], r[i], t[i], camera_mat, dist_coef)
            error = cv2.norm(image_points[i], image_points2, cv2.NORM_L2) / len(image_points2)
            mean_error += error
        print "total error: ", mean_error/len(object_points) #A value close to 0 is desirable(Not suitable for evaluation of fisheye lenses?)
    else:
        print "findChessboardCorners() not be successful once"

#Distortion correction image display
if camera_mat != []:
    while(True):
        ret, frame = video_input.read()
        undistort_image = cv2.undistort(frame, camera_mat, dist_coef)

        cv2.imshow('original', frame)
        cv2.imshow('undistort', undistort_image)
        c = cv2.waitKey(50) & 0xFF
        if c==27: # ESC
            break

video_input.release()
cv2.destroyAllWindows()

that's all.

Recommended Posts

[Windows] [Python] Camera calibration of fisheye lens with OpenCV
Camera capture with Python + OpenCV
Face recognition with camera with opencv3 + python2.7
Basic study of OpenCV with Python
Image acquisition from camera with Python + OpenCV
Performance comparison of face detector with Python + OpenCV
Install OpenCV 4.0 and Python 3.7 on Windows 10 with Anaconda
Binarization with OpenCV / Python
Python starting with Windows 7
Python, OpenCV camera capture
[OpenCV / Python] I tried image analysis of cells with OpenCV
Try projective transformation of images using OpenCV with Python
Summary of tools for operating Windows GUI with Python
Display USB camera video with Python OpenCV with Raspberry Pi
I tried "morphology conversion" of images with Python + OpenCV
Python with VS Code (Windows 10)
Run python with PyCharm (Windows)
"Apple processing" with OpenCV3 + Python3
Image editing with python OpenCV
[Python] Using OpenCV with Python (Basic)
Face detection with Python + OpenCV
Time synchronization (Windows) with Python
Using OpenCV with Python @Mac
I tried "gamma correction" of the image with Python + OpenCV
Estimate the attitude of AR markers with Python + OpenCV + drone
[Python] Easy reading of serial number image files with OpenCV
Environment construction of python and opencv
Shining life with Python and OpenCV
Face detection with YOLO Face (Windows10, Python3.6)
Use PointGrey camera with Python (PyCapture2)
[Python] Using OpenCV with Python (Image Filtering)
Neural network with OpenCV 3 and Python 3
Color extraction with Python + OpenCV solved the mystery of the green background
[Python] Using OpenCV with Python (Image transformation)
[Python] Using OpenCV with Python (Edge Detection)
How to make a surveillance camera (Security Camera) with Opencv and Python
Getting Started with Python Basics of Python
Easy Python + OpenCV programming with Canopy
Life game with Python! (Conway's Game of Life)
Build mlpy with python3.3 (64bit) (windows 64bit)
10 functions of "language with battery" python
Installation of Python, SciPy, matplotlib (Windows)
Cut out face with Python + OpenCV
Load gif images with Python + OpenCV
Use camera calibration file with OpenCvSharp4
Implementation of Dijkstra's algorithm with python
Find image similarity with Python + OpenCV
Draw an illustration with Python + OpenCV
Getting started with Python 3.8 on Windows
Coexistence of Python2 and 3 with CircleCI (1.0)
Track baseball balls with Python + OpenCV
[Python] Creating multiple windows with Tkinter
Graph Based Segmentation with Python + OpenCV
Draw arrows (vectors) with opencv / python
The fastest way to get camera images regularly with python opencv
[Python Windows] pip install with Python version
[OpenCV; Python] Summary of findcontours function
How to crop the lower right part of the image with Python OpenCV
Create your own virtual camera with Python + OpenCV and apply original effects
Get and estimate the shape of the head using Dlib and OpenCV with python
Basics of binarized image processing with Python