Commit 54e1b98e authored by Matvey Safroshkin's avatar Matvey Safroshkin
Browse files

initial Oslab_aruco_ccalib commit

parent 4f0eb078
cmake_minimum_required(VERSION 3.8)
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/aruco)
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/OSLabDetector)
add_subdirectory(${CMAKE_CURRENT_LIST_DIR}/ccalib)
file(GLOB EXPERIMENTAL_SOURCES experimental/*.cpp experimental/*.h)
set (TARGET EXPERIMENTAL_EXEC)
add_executable(${TARGET} ${EXPERIMENTAL_SOURCES})
message(STATUS ${CCALIB_INCLUDE})
message(STATUS ${ARUCO_INCLUDE})
target_include_directories(${TARGET} PRIVATE ${CCALIB_INCLUDE} ${ARUCO_INCLUDE} ${OPENCV_INCLUDE} ${OSLabDetector_INCLUDE})
target_link_libraries(${TARGET} ${OpenCV_LIBS} ${CCALIB_LIBRARY} ${ARUCO_LIBRARY})
\ No newline at end of file
file(GLOB OSLabDetector_SOURCES include/*.h include/*.hpp src/*.cpp )
find_package(OpenCV REQUIRED)
set(OSLabDetector_INCLUDE ${CMAKE_CURRENT_LIST_DIR}/include)
set(OSLabDetector_LIBRARY OSLabDetector_LIBRARY)
set(OSLabDetector_INCLUDE ${OSLabDetector_INCLUDE} ${ARUCO_INCLUDE} PARENT_SCOPE)
set(OSLabDetector_LIBRARY ${OSLabDetector_LIBRARY} PARENT_SCOPE)
add_library (${OSLabDetector_LIBRARY} ${OSLabDetector_SOURCES} )
MESSAGE(STATUS OSLabDetector_INCLUDE)
MESSAGE(STATUS ${OSLabDetector_INCLUDE})
target_include_directories(${OSLabDetector_LIBRARY} PRIVATE ${ARUCO_INCLUDE} ${OPENCV_INCLUDE} ${OSLabDetector_INCLUDE})
target_link_libraries(${OSLabDetector_LIBRARY} ${OpenCV_LIBS} ${ARUCO_LIBRARY})
\ No newline at end of file
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2015, Baisheng Lai (laibaisheng@gmail.com), Zhejiang University,
// all rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#pragma once
#ifndef __OSLAB_CHARUCOBOARDFINDER_HPP__
#define __OSLAB_CHARUCOBOARDFINDER_HPP__
#include "opencv2/features2d.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/core/types.hpp"
#include "CharucoGridCornerDetecor.h"
namespace cv {
namespace randpattern {
//! @addtogroup ccalib
//! @{
/** @brief Class for finding features points and corresponding 3D in world coordinate of
a "random" pattern, which can be to be used in calibration. It is useful when pattern is
partly occluded or only a part of pattern can be observed in multiple cameras calibration.
The pattern can be generated by RandomPatternGenerator class described in this file.
Please refer to paper
B. Li, L. Heng, K. Kevin and M. Pollefeys, "A Multiple-Camera System
Calibration Toolbox Using A Feature Descriptor-Based Calibration
Pattern", in IROS 2013.
*/
class CV_EXPORTS CHarucoBoardCornerFinder
{
public:
/* @brief Construct CHarucoBoardCornerFinder object
@param patternWidth the real width of "random" pattern in a user defined unit.
@param patternHeight the real height of "random" pattern in a user defined unit.
@param nMiniMatch number of minimal matches, otherwise that image is abandoned
@depth depth of output objectPoints and imagePoints, set it to be CV_32F or CV_64F.
@showExtraction whether show feature extraction, 0 for no and 1 for yes.
@detector feature detector to detect feature points in pattern and images.
*/
CHarucoBoardCornerFinder(float patternWidth, float patternHeight,
int nminiMatch = 20, int depth = CV_32F, int verbose = 0, int showExtraction = 0,
Ptr<FeatureDetector> detector = new CharucoGridCornerDetector);
/* @brief Load pattern image and compute features for pattern
@param patternImage image for "random" pattern generated by RandomPatternGenerator, run it first.
*/
void loadBoard(const cv::Mat &patternImage);
/* @brief Load pattern and features
@param patternImage image for "random" pattern generated by RandomPatternGenerator, run it first.
@param patternKeyPoints keyPoints created from a FeatureDetector.
@param patternDescriptors descriptors created from a DescriptorExtractor.
*/
void loadBoard(const cv::Mat &patternImage, const std::vector<cv::KeyPoint> &patternKeyPoints, const cv::Mat &patternDescriptors);
/* @brief Load pattern and features
@param squaresX Number of squares in X direction
@param squaresY Number of squares in Y direction
@param squareLength Square side length (in pixels)
@param markerLength Marker side length (in pixels)
@param dictionaryId DICT_4X4_50=0, DICT_4X4_100=1, DICT_4X4_250=2,"
"DICT_4X4_1000=3, DICT_5X5_50=4, DICT_5X5_100=5, DICT_5X5_250=6, DICT_5X5_1000=7, "
"DICT_6X6_50=8, DICT_6X6_100=9, DICT_6X6_250=10, DICT_6X6_1000=11, DICT_7X7_50=12,"
"DICT_7X7_100=13, DICT_7X7_250=14, DICT_7X7_1000=15, DICT_ARUCO_ORIGINAL = 16}"
@param borderBits Number of bits in marker borders
@param showImage show generated image
*/
void generateBoard(size_t squaresX, size_t squaresY, size_t squareLength, size_t markerLength, size_t dictionaryId, size_t borderBits , bool showImage);
/* @brief Compute matched object points and image points which are used for calibration
The objectPoints (3D) and imagePoints (2D) are stored inside the class. Run getObjectPoints()
and getImagePoints() to get them.
@param inputImages vector of 8-bit grayscale images containing "random" pattern
that are used for calibration.
*/
void computeObjectImagePoints(std::vector<cv::Mat> inputImages);
//void computeObjectImagePoints2(std::vector<cv::Mat> inputImages);
/* @brief Compute object and image points for a single image. It returns a vector<Mat> that
the first element stores the imagePoints and the second one stores the objectPoints.
@param inputImage single input image for calibration
*/
std::vector<cv::Mat> computeObjectImagePointsForSingle(cv::Mat inputImage);
/* @brief Get object(3D) points
*/
const std::vector<cv::Mat> &getObjectPoints();
/* @brief and image(2D) points
*/
const std::vector<cv::Mat> &getImagePoints();
private:
std::vector<cv::Mat> _objectPonits, _imagePoints;
float _patternWidth, _patternHeight;
cv::Size _patternImageSize;
int _nminiMatch;
int _depth;
int _verbose;
Ptr<FeatureDetector> _detector;
Ptr<DescriptorExtractor> _descriptor;
Ptr<DescriptorMatcher> _matcher;
Mat _descriptorPattern;
std::vector<cv::KeyPoint> _keypointsPattern;
Mat _patternImage;
int _showExtraction;
void keyPoints2MatchedLocation(const std::vector<cv::KeyPoint>& imageKeypoints,
const std::vector<cv::KeyPoint>& patternKeypoints, const std::vector<cv::DMatch> matchces,
cv::Mat& matchedImagelocation, cv::Mat& matchedPatternLocation);
void getFilteredLocation(cv::Mat& imageKeypoints, cv::Mat& patternKeypoints, const cv::Mat mask);
void getObjectImagePoints(const cv::Mat& imageKeypoints, const cv::Mat& patternKeypoints);
void crossCheckMatching(cv::Ptr<DescriptorMatcher>& descriptorMatcher,
const Mat& descriptors1, const Mat& descriptors2,
std::vector<DMatch>& filteredMatches12, int knn = 1);
void corssCheckMatching(std::vector <cv::KeyPoint>& imagePoints,
std::vector <cv::KeyPoint> patternPoints, std::vector<DMatch>& filteredMatches);
void drawCorrespondence(const Mat& image1, const std::vector<cv::KeyPoint> keypoint1,
const Mat& image2, const std::vector<cv::KeyPoint> keypoint2, const std::vector<cv::DMatch> matchces,
const Mat& mask1, const Mat& mask2, const int step);
};
/* @brief Class to generate "random" pattern image that are used for RandomPatternCornerFinder
Please refer to paper
B. Li, L. Heng, K. Kevin and M. Pollefeys, "A Multiple-Camera System
Calibration Toolbox Using A Feature Descriptor-Based Calibration
Pattern", in IROS 2013.
*/
}
} //namespace randpattern, cv
#endif
\ No newline at end of file
#pragma once
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/features2d.hpp>
#include "opencv2/core/types.hpp"
#include <opencv2/aruco/charuco.hpp>
#include <opencv2/aruco/dictionary.hpp>
class CharucoGridCornerDetector : public cv::FeatureDetector
{
/*
"{@outfile |<none> | Output image }"
"{w | | Number of squares in X direction }"
"{h | | Number of squares in Y direction }"
"{sl | | Square side length (in pixels) }"
"{ml | | Marker side length (in pixels) }"
"{d | | dictionary: DICT_4X4_50=0, DICT_4X4_100=1, DICT_4X4_250=2,"
"DICT_4X4_1000=3, DICT_5X5_50=4, DICT_5X5_100=5, DICT_5X5_250=6, DICT_5X5_1000=7, "
"DICT_6X6_50=8, DICT_6X6_100=9, DICT_6X6_250=10, DICT_6X6_1000=11, DICT_7X7_50=12,"
"DICT_7X7_100=13, DICT_7X7_250=14, DICT_7X7_1000=15, DICT_ARUCO_ORIGINAL = 16}"
"{m | | Margins size (in pixels). Default is (squareLength-markerLength) }"
"{bb | 1 | Number of bits in marker borders }"
"{si | false | show generated image }";
*/
int m_borderBits = 1;
int m_squaresX = 12;
int m_squaresY = 9;
float m_squareLength = 60;
float m_markerLength = 45;
int m_dictionaryId = 5;
bool m_showRejected = true;
bool m_refindStrategy = false;
cv::Ptr<cv::aruco::Dictionary> m_dictionary = nullptr;
cv::Ptr<cv::aruco::CharucoBoard> m_charucoboard = nullptr;
cv::Ptr<cv::aruco::Board> m_board = nullptr;
cv::Ptr<cv::aruco::DetectorParameters> m_detectorParams = nullptr;
cv::Mat camMatrix;
cv::Mat distCoeffs;
public:
CharucoGridCornerDetector();
~CharucoGridCornerDetector();
virtual void detect(cv::InputArray image, CV_OUT std::vector<cv::KeyPoint>& keypoints, cv::InputArray mask = cv::noArray()) override;
void detectMat(cv::Mat &image, std::vector< cv::KeyPoint > &keypoints, const cv::Mat &mask = cv::Mat());
};
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2015, Baisheng Lai (laibaisheng@gmail.com), Zhejiang University,
// all rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
/**
* This module was accepted as a GSoC 2015 project for OpenCV, authored by
* Baisheng Lai, mentored by Bo Li.
* This module implements points extraction from a "random" pattern image.
* It returns 3D object points and 2D image pixels that can be used for calibration.
* Compared with traditional calibration object like chessboard, it is useful when pattern is
* partly occluded or only a part of pattern can be observed in multiple cameras calibration.
* For detail, refer to this paper
* B. Li, L. Heng, K. Kevin and M. Pollefeys, "A Multiple-Camera System
* Calibration Toolbox Using A Feature Descriptor-Based Calibration
* Pattern", in IROS 2013.
*/
#include "CharucoBoardCornerFinder.h"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include "opencv2/features2d.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/core/types.hpp"
#include <opencv2/aruco.hpp>
#include <opencv2/aruco/charuco.hpp>
#include "CharucoGridCornerDetecor.h"
using namespace std;
namespace cv {
namespace randpattern {
/*CHarucoBoardCornerFinder::CHarucoBoardCornerFinder(float patternWidth, float patternHeight,
int nminiMatch, int depth, int verbose, int showExtraction, Ptr<FeatureDetector> detector, Ptr<DescriptorExtractor> descriptor,
Ptr<DescriptorMatcher> matcher)
{
_patternHeight = patternHeight;
_patternWidth = patternWidth;
_nminiMatch = nminiMatch;
_objectPonits.resize(0);
_imagePoints.resize(0);
_depth = depth;
_detector = detector;
_descriptor = descriptor;
_matcher = matcher;
_showExtraction = showExtraction;
_verbose = verbose;
}
*/
CHarucoBoardCornerFinder::CHarucoBoardCornerFinder(float patternWidth, float patternHeight,
int nminiMatch, int depth, int verbose , int showExtraction,
Ptr<FeatureDetector> detector)
{
_patternHeight = patternHeight;
_patternWidth = patternWidth;
_nminiMatch = nminiMatch;
_objectPonits.resize(0);
_imagePoints.resize(0);
_depth = depth;
_detector = detector;
_showExtraction = showExtraction;
_verbose = verbose;
}
void CHarucoBoardCornerFinder::computeObjectImagePoints(std::vector<cv::Mat> inputImages)
{
CV_Assert(!_patternImage.empty());
CV_Assert(inputImages.size() > 0);
int nImages = (int)inputImages.size();
std::vector<Mat> imageObjectPoints;
for (int i = 0; i < nImages; ++i)
{
imageObjectPoints = computeObjectImagePointsForSingle(inputImages[i]);
if ((int)imageObjectPoints[0].total() > _nminiMatch)
{
_imagePoints.push_back(imageObjectPoints[0]);
_objectPonits.push_back(imageObjectPoints[1]);
}
}
}
void CHarucoBoardCornerFinder::keyPoints2MatchedLocation(const std::vector<cv::KeyPoint>& imageKeypoints,
const std::vector<cv::KeyPoint>& patternKeypoints, const std::vector<DMatch> matchces,
cv::Mat& matchedImagelocation, cv::Mat& matchedPatternLocation)
{
matchedImagelocation.release();
matchedPatternLocation.release();
std::vector<Vec2d> image, pattern;
for (int i = 0; i < (int)matchces.size(); ++i)
{
Point2f imgPt = imageKeypoints[matchces[i].queryIdx].pt;
Point2f patPt = patternKeypoints[matchces[i].trainIdx].pt;
image.push_back(Vec2d(imgPt.x, imgPt.y));
pattern.push_back(Vec2d(patPt.x, patPt.y));
}
Mat(image).convertTo(matchedImagelocation, CV_64FC2);
Mat(pattern).convertTo(matchedPatternLocation, CV_64FC2);
}
void CHarucoBoardCornerFinder::getFilteredLocation(cv::Mat& imageKeypoints, cv::Mat& patternKeypoints, const cv::Mat mask)
{
Mat tmpKeypoint, tmpPattern;
imageKeypoints.copyTo(tmpKeypoint);
patternKeypoints.copyTo(tmpPattern);
imageKeypoints.release();
patternKeypoints.release();
std::vector<cv::Vec2d> vecKeypoint, vecPattern;
for (int i = 0; i < (int)mask.total(); ++i)
{
if (mask.at<uchar>(i) == 1)
{
vecKeypoint.push_back(tmpKeypoint.at<Vec2d>(i));
vecPattern.push_back(tmpPattern.at<Vec2d>(i));
}
}
Mat(vecKeypoint).convertTo(imageKeypoints, CV_64FC2);
Mat(vecPattern).convertTo(patternKeypoints, CV_64FC2);
}
void CHarucoBoardCornerFinder::getObjectImagePoints(const cv::Mat& imageKeypoints, const cv::Mat& patternKeypoints)
{
Mat imagePoints_i, objectPoints_i;
int imagePointsType = CV_MAKETYPE(_depth, 2);
int objectPointsType = CV_MAKETYPE(_depth, 3);
imageKeypoints.convertTo(imagePoints_i, imagePointsType);
_imagePoints.push_back(imagePoints_i);
if (patternKeypoints.total() != CV_64FC2)
patternKeypoints.convertTo(patternKeypoints, CV_64FC2);
std::vector<Vec3d> objectPoints;
for (int i = 0; i < (int)patternKeypoints.total(); ++i)
{
double x = patternKeypoints.at<Vec2d>(i)[0];
double y = patternKeypoints.at<Vec2d>(i)[1];
x = x / _patternImageSize.width * _patternWidth;
y = y / _patternImageSize.height * _patternHeight;
objectPoints.push_back(Vec3d(x, y, 0));
}
Mat(objectPoints).convertTo(objectPoints_i, objectPointsType);
_objectPonits.push_back(objectPoints_i);
}
void CHarucoBoardCornerFinder::crossCheckMatching(Ptr<DescriptorMatcher>& descriptorMatcher,
const Mat& descriptors1, const Mat& descriptors2,
std::vector<DMatch>& filteredMatches12, int knn)
{
filteredMatches12.clear();
DMatch d;
std::vector<std::vector<DMatch> > matches12, matches21;
descriptorMatcher->knnMatch(descriptors1, descriptors2, matches12, knn);
descriptorMatcher->knnMatch(descriptors2, descriptors1, matches21, knn);
for (size_t m = 0; m < matches12.size(); m++)
{
bool findCrossCheck = false;
for (size_t fk = 0; fk < matches12[m].size(); fk++)
{
DMatch forward = matches12[m][fk];
for (size_t bk = 0; bk < matches21[forward.trainIdx].size(); bk++)
{
DMatch backward = matches21[forward.trainIdx][bk];
if (backward.trainIdx == forward.queryIdx)
{
filteredMatches12.push_back(forward);
findCrossCheck = true;
break;
}
}
if (findCrossCheck) break;
}
}
}
void CHarucoBoardCornerFinder::corssCheckMatching(std::vector <cv::KeyPoint>& imagePoints,
std::vector <cv::KeyPoint> patternPoints, std::vector<DMatch>& filteredMatches)
{
filteredMatches.clear();
for (size_t i = 0; i < patternPoints.size(); ++i)
{
for (size_t j = 0; j < imagePoints.size(); ++j)
{
if (patternPoints[i].class_id == imagePoints[j].class_id)
{
DMatch d;
d.trainIdx = i;
d.queryIdx = j;
d.imgIdx = j;
filteredMatches.push_back(d);
}
}
}
}
void CHarucoBoardCornerFinder::drawCorrespondence(const Mat& image1, const std::vector<cv::KeyPoint> keypoint1,
const Mat& image2, const std::vector<cv::KeyPoint> keypoint2, const std::vector<cv::DMatch> matchces,
const Mat& mask1, const Mat& mask2, const int step)
{
Mat img_corr;
if (step == 1)
{
drawMatches(image1, keypoint1, image2, keypoint2, matchces, img_corr);
}
else if (step == 2)
{
std::vector<cv::DMatch> matchesFilter;
for (int i = 0; i < (int)mask1.total(); ++i)
{
if (!mask1.empty() && mask1.at<uchar>(i) == 1)
{
matchesFilter.push_back(matchces[i]);
}
}
drawMatches(image1, keypoint1, image2, keypoint2, matchesFilter, img_corr);
}
else if (step == 3)
{
std::vector<cv::DMatch> matchesFilter;
int j = 0;
for (int i = 0; i < (int)mask1.total(); ++i)
{
if (mask1.at<uchar>(i) == 1)
{
if (!mask2.empty() && mask2.at<uchar>(j) == 1)
{
matchesFilter.push_back(matchces[i]);
}
j++;
}
}
drawMatches(image1, keypoint1, image2, keypoint2, matchesFilter, img_corr);
}
cv::resize(img_corr, img_corr, cv::Size(), 0.5, 0.5);
imshow("correspondence", img_corr);
waitKey(100);
}
const std::vector<cv::Mat> &CHarucoBoardCornerFinder::getObjectPoints()
{
return _objectPonits;
}
const std::vector<cv::Mat> &CHarucoBoardCornerFinder::getImagePoints()
{
return _imagePoints;
}
void CHarucoBoardCornerFinder::loadBoard(const cv::Mat &patternImage)
{
_patternImage = patternImage.clone();
if (_patternImage.type() != CV_8U)
_patternImage.convertTo(_patternImage, CV_8U);
_patternImageSize = _patternImage.size();
_detector->detect(patternImage, _keypointsPattern);
//_descriptor->compute(patternImage, _keypointsPattern, _descriptorPattern);
//_descriptorPattern.convertTo(_descriptorPattern, CV_32F);
}
void CHarucoBoardCornerFinder::loadBoard(const cv::Mat &patternImage, const std::vector<cv::KeyPoint> &patternKeyPoints, const cv::Mat &patternDescriptors)
{
CV_Assert((int)patternKeyPoints.size() == patternDescriptors.rows);
CV_Assert(patternDescriptors.cols == _descriptor->descriptorSize());
CV_Assert(patternDescriptors.type() == _descriptor->descriptorType());
_patternImage = patternImage.clone();
if (_patternImage.type() != CV_8U)
_patternImage.convertTo(_patternImage, CV_8U);
_patternImageSize = patternImage.size();