def readCalibrationParams(self, path): parser = JSONParser() jsonObj = parser.parse(path) self.calibrationMatrix = np.array(jsonObj['cameraMatrix'],np.float32) ret, self.inverseCalibrationMatrix = cv2.invert(self.calibrationMatrix) self.distortCoefs = np.array(jsonObj['distortedCoefficients'], np.float32)
def calibrate(self, confFile, output): parser = JSONParser() jsonObj = parser.parseCameraConf(confFile, self.id) print 'Calibration status: parsing configuration file' if jsonObj is None: print 'Wrong conf file' return None print 'Calibration status: parsing finished' patternSize = (jsonObj['patternWidth']-1,jsonObj['patternHeight']-1) patternPoints = np.zeros((np.prod(patternSize), 3), np.float32) patternPoints[:, :2] = np.indices(patternSize).T.reshape(-1, 2) patternPoints *= jsonObj['squareSize'] w, h = self.resolution[0], self.resolution[1] objPoints = [] imgPoints = [] frameCnt = 0 frameDelay = int((jsonObj['inputDelay']/1000.0)*60) print 'Calibration status: selecting frames for calibration' while(1): ret, frame = self.capture.read() if (ret is True) and ((frameCnt % frameDelay) == 0): if(jsonObj['flipAroundHorizontalAxis'] is True): cv2.flip(frame, 0, frame) found, corners = cv2.findChessboardCorners(frame,patternSize) if found: term = (cv2.TERM_CRITERIA_EPS*cv2.TERM_CRITERIA_COUNT, 30, 0.1) cvtFrame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) cv2.cornerSubPix(cvtFrame,corners,(5,5),(-1,-1), term) else: continue imgPoints.append(corners.reshape(-1,2)) objPoints.append(patternPoints) if(len(imgPoints) == jsonObj['numOfFrames']): break frameCnt += 1 print 'Calibration status: frames selected' print 'Calibration status: started calibration' rms, cameraMatrix, distCoefs, rvecs, tvecs = cv2.calibrateCamera(objPoints, imgPoints, (int(w), int(h)), self.getFlags(jsonObj), None) print 'Calibration status: calibration finished' self.calibrationMatrix = cameraMatrix ret, self.inverseCalibrationMatrix = cv2.invert(cameraMatrix) self.distortCoefs = distCoefs print "Calibration status: writing results to file" object = {'id':self.id, 'cameraMatrix': cameraMatrix.tolist(), 'distortedCoefficients': distCoefs.tolist()} jsonObj = json.dumps(object) parser.writeJSON(jsonObj,output) print("RMS:", rms)