id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
26,541
common.h
danmar_cppcheck/gui/common.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef COMMON_H #define COMMON_H #include <cstdint> #include <QMap> #include <QString> /// @addtogroup GUI /// @{ #define CLANG_ANALYZER "clang-analyzer" #define CLANG_TIDY "clang-tidy" /** * QSetting value names */ // Window/dialog sizes #define SETTINGS_WINDOW_MAXIMIZED "Window maximized" #define SETTINGS_WINDOW_WIDTH "Window width" #define SETTINGS_WINDOW_HEIGHT "Window height" #define SETTINGS_MAINWND_SPLITTER_STATE "Mainwindow/Vertical splitter state" #define SETTINGS_CHECK_DIALOG_WIDTH "Check dialog width" #define SETTINGS_CHECK_DIALOG_HEIGHT "Check dialog height" #define SETTINGS_PROJECT_DIALOG_WIDTH "Project dialog width" #define SETTINGS_PROJECT_DIALOG_HEIGHT "Project dialog height" // Main window settings #define SETTINGS_RESULT_COLUMN_WIDTH "Result column %1 width" #define SETTINGS_TOOLBARS_MAIN_SHOW "Toolbars/ShowStandard" #define SETTINGS_TOOLBARS_VIEW_SHOW "Toolbars/ShowView" #define SETTINGS_TOOLBARS_FILTER_SHOW "Toolbars/ShowFilter" // Report type #define SETTINGS_REPORT_TYPE "Report type" enum class ReportType : std::uint8_t { normal=0, autosar=1, certC=2, certCpp=3, misraC=4, misraCpp2008=5, misraCpp2023=6 }; // Show * states #define SETTINGS_SHOW_STYLE "Show style" #define SETTINGS_SHOW_ERRORS "Show errors" #define SETTINGS_SHOW_WARNINGS "Show warnings" #define SETTINGS_SHOW_PERFORMANCE "Show performance" #define SETTINGS_SHOW_INFORMATION "Show information" #define SETTINGS_SHOW_PORTABILITY "Show portability" // Standards support #define SETTINGS_STD_CPP "Standard CPP" #define SETTINGS_STD_C "Standard C" // Language enforcement #define SETTINGS_ENFORCED_LANGUAGE "Enforced language" // Other settings #define SETTINGS_CHECK_FORCE "Check force" #define SETTINGS_CHECK_THREADS "Check threads" #define SETTINGS_SHOW_FULL_PATH "Show full path" #define SETTINGS_SHOW_NO_ERRORS "Show no errors message" #define SETTINGS_SHOW_DEBUG_WARNINGS "Show debug warnings" #define SETTINGS_SAVE_ALL_ERRORS "Save all errors" #define SETTINGS_SAVE_FULL_PATH "Save full path" #define SETTINGS_APPLICATION_NAMES "Application names" #define SETTINGS_APPLICATION_PATHS "Application paths" #define SETTINGS_APPLICATION_PARAMS "Application parameters" #define SETTINGS_APPLICATION_DEFAULT "Default Application" #define SETTINGS_LANGUAGE "Application language" #define SETTINGS_GLOBAL_INCLUDE_PATHS "Global include paths" #define SETTINGS_PYTHON_PATH "Python path" #define SETTINGS_MISRA_FILE "MISRA C 2012 file" #define SETTINGS_CLANG_PATH "Clang path" #define SETTINGS_VS_INCLUDE_PATHS "VS include paths" #define SETTINGS_INLINE_SUPPRESSIONS "Inline suppressions" #define SETTINGS_INCONCLUSIVE_ERRORS "Inconclusive errors" #define SETTINGS_MRU_PROJECTS "MRU Projects" #define SETTINGS_SHOW_ERROR_ID "Show error Id" #define SETTINGS_SHOW_STATISTICS "Show statistics" #define SETTINGS_OPEN_PROJECT "Open Project" #define SETTINGS_CHECK_VERSION "Check Version" #define SETTINGS_CHECK_FOR_UPDATES "Check for updates" // The maximum value for the progress bar #define PROGRESS_MAX 1024.0 #define SETTINGS_CHECKED_PLATFORM "Checked platform" #define SETTINGS_LAST_CHECK_PATH "Last check path" #define SETTINGS_LAST_PROJECT_PATH "Last project path" #define SETTINGS_LAST_RESULT_PATH "Last result path" #define SETTINGS_LAST_SOURCE_PATH "Last source path" #define SETTINGS_LAST_APP_PATH "Last application path" #define SETTINGS_LAST_ANALYZE_FILES_FILTER "Last analyze files filter" /** * @brief Obtains the path of specified type * Returns the path of specified type if not empty. Otherwise returns last check * path if valid or user's home directory. * @param type Type of path to obtain * @return Best path for provided type */ QString getPath(const QString &type); /** * @brief Stores last used path of specified type * Stores provided path as last used path for specified type. * @param type Type of the path to store * @param value Path to store */ void setPath(const QString &type, const QString &value); /** * @brief Creates a string suitable for passing as the filter argument to * methods like QFileDialog::getOpenFileName. * @param filters A map of filter descriptions to the associated file name * patterns. * @param addAllSupported If set to true (the default), the function will * include a filter entry containing all the file name patterns found in * \p filters. This entry will be the first in the resulting filter string. * @param addAll If set to true (the default), the function will * include a filter entry displaying all files. This entry will be placed * after the entry for \p addAllSupported files. * * Example usage: * * @code * QMap<QString,QString> filters; * filters[tr("Supported images")] = "*.bmp *.jpg *.png"; * filters[tr("Plain text")] = "*.txt"; * * const QString filterString = toFilterString(filters); * * // filterString contains "All supported files (*.txt *.bmp *.jpg *.png);;All files (*.*);;Plain text (*.txt);;Supported images (*.bmp *.jpg *.png)" * @endcode */ QString toFilterString(const QMap<QString,QString>& filters, bool addAllSupported=true, bool addAll=true); /** * Get configured data dir. If not configured then it will try to determine that from exe path. */ QString getDataDir(); /// @} #endif
6,384
C++
.h
139
44.381295
150
0.731319
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,544
projectfile.h
danmar_cppcheck/gui/projectfile.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PROJECT_FILE_H #define PROJECT_FILE_H #include "settings.h" #include "suppressions.h" #include <cstddef> #include <cstdint> #include <map> #include <utility> #include <QList> #include <QObject> #include <QString> #include <QStringList> class QXmlStreamReader; class QXmlStreamWriter; /// @addtogroup GUI /// @{ /** * @brief A class that reads and writes project files. * The project files contain project-specific settings for checking. For * example a list of include paths. */ class ProjectFile : public QObject { Q_OBJECT public: explicit ProjectFile(QObject *parent = nullptr); explicit ProjectFile(QString filename, QObject *parent = nullptr); ~ProjectFile() override { if (this == mActiveProject) mActiveProject = nullptr; } enum class CheckLevel : std::uint8_t { normal, exhaustive }; static ProjectFile* getActiveProject() { return mActiveProject; } void setActiveProject() { mActiveProject = this; } /** * @brief Read the project file. * @param filename Filename (can be also given to constructor). */ bool read(const QString &filename = QString()); /** * @brief Get project root path. * @return project root path. */ const QString& getRootPath() const { return mRootPath; } const QString& getBuildDir() const { return mBuildDir; } const QString& getImportProject() const { return mImportProject; } bool getAnalyzeAllVsConfigs() const { return mAnalyzeAllVsConfigs; } bool getCheckHeaders() const { return mCheckHeaders; } void setCheckHeaders(bool b) { mCheckHeaders = b; } bool getCheckUnusedTemplates() const { return mCheckUnusedTemplates; } void setCheckUnusedTemplates(bool b) { mCheckUnusedTemplates = b; } bool getInlineSuppression() const { return mInlineSuppression; } void setInlineSuppression(bool b) { mInlineSuppression = b; } /** * @brief Get list of include directories. * @return list of directories. */ QStringList getIncludeDirs() const { return ProjectFile::fromNativeSeparators(mIncludeDirs); } /** * @brief Get list of defines. * @return list of defines. */ const QStringList& getDefines() const { return mDefines; } /** * @brief Get list of undefines. * @return list of undefines. */ const QStringList& getUndefines() const { return mUndefines; } /** * @brief Get list of paths to check. * @return list of paths. */ QStringList getCheckPaths() const { return ProjectFile::fromNativeSeparators(mPaths); } /** * @brief Get list of paths to exclude from the check. * @return list of paths. */ QStringList getExcludedPaths() const { return ProjectFile::fromNativeSeparators(mExcludedPaths); } /** * @brief Get list of paths to exclude from the check. * @return list of paths. */ const QStringList& getVsConfigurations() const { return mVsConfigurations; } /** * @brief Get list libraries. * @return list of libraries. */ const QStringList& getLibraries() const { return mLibraries; } /** * @brief Get platform. * @return Current platform. If it ends with .xml then it is a file. Otherwise it must match one of the return values from @sa cppcheck::Platform::toString() ("win32A", "unix32", ..) */ const QString& getPlatform() const { return mPlatform; } const QString& getProjectName() const { return mProjectName; } void setProjectName(QString projectName) { mProjectName = std::move(projectName); } /** * @brief Get "raw" suppressions. * @return list of suppressions. */ const QList<SuppressionList::Suppression>& getSuppressions() const { return mSuppressions; } /** * @brief Get "checking" suppressions. Relative paths are converted to absolute paths. * @return list of suppressions. */ QList<SuppressionList::Suppression> getCheckingSuppressions() const; /** * @brief Get list addons. * @return list of addons. */ const QStringList& getAddons() const { return mAddons; } /** * @brief Get path to addon python script * @param filesDir Data files folder set by --data-dir * @param addon addon i.e. "misra" to lookup */ static QString getAddonFilePath(QString filesDir, const QString &addon); /** * @brief Get list of addons and tools. * @return list of addons and tools. */ QStringList getAddonsAndTools() const; bool getClangAnalyzer() const { return false; //mClangAnalyzer; } void setClangAnalyzer(bool c) { mClangAnalyzer = c; } bool getClangTidy() const { return mClangTidy; } void setClangTidy(bool c) { mClangTidy = c; } const QStringList& getTags() const { return mTags; } int getMaxCtuDepth() const { return mMaxCtuDepth; } void setMaxCtuDepth(int maxCtuDepth) { mMaxCtuDepth = maxCtuDepth; } int getMaxTemplateRecursion() const { return mMaxTemplateRecursion; } void setMaxTemplateRecursion(int maxTemplateRecursion) { mMaxTemplateRecursion = maxTemplateRecursion; } /** * @brief Get filename for the project file. * @return file name. */ const QString& getFilename() const { return mFilename; } /** * @brief Set project root path. * @param rootpath new project root path. */ void setRootPath(const QString &rootpath) { mRootPath = rootpath; } void setBuildDir(const QString &buildDir) { mBuildDir = buildDir; } void setImportProject(const QString &importProject) { mImportProject = importProject; } void setAnalyzeAllVsConfigs(bool b) { mAnalyzeAllVsConfigs = b; } /** * @brief Set list of includes. * @param includes List of defines. */ void setIncludes(const QStringList &includes); /** * @brief Set list of defines. * @param defines List of defines. */ void setDefines(const QStringList &defines); /** * @brief Set list of undefines. * @param undefines List of undefines. */ void setUndefines(const QStringList &undefines); /** * @brief Set list of paths to check. * @param paths List of paths. */ void setCheckPaths(const QStringList &paths); /** * @brief Set list of paths to exclude from the check. * @param paths List of paths. */ void setExcludedPaths(const QStringList &paths); /** * @brief Set list of libraries. * @param libraries List of libraries. */ void setLibraries(const QStringList &libraries); /** * @brief Set platform. * @param platform platform. */ void setPlatform(const QString &platform); /** * @brief Set list of suppressions. * @param suppressions List of suppressions. */ void setSuppressions(const QList<SuppressionList::Suppression> &suppressions); /** Add suppression */ void addSuppression(const SuppressionList::Suppression &suppression); /** * @brief Set list of addons. * @param addons List of addons. */ void setAddons(const QStringList &addons); /** @brief Set list of Visual Studio configurations to be checked * @param vsConfigs List of configurations */ void setVSConfigurations(const QStringList &vsConfigs); /** CheckLevel: normal/exhaustive */ void setCheckLevel(CheckLevel checkLevel); bool isCheckLevelExhaustive() const; /** * @brief Set tags. * @param tags tag list */ void setTags(const QStringList &tags) { mTags = tags; } /** Set tags for a warning */ void setWarningTags(std::size_t hash, const QString& tags); /** Get tags for a warning */ QString getWarningTags(std::size_t hash) const; /** Bughunting (Cppcheck Premium) */ void setBughunting(bool bughunting) { mBughunting = bughunting; } bool getBughunting() const { return mBughunting; } /** @brief Get list of coding standards (checked by Cppcheck Premium). */ const QStringList& getCodingStandards() const { return mCodingStandards; } /** * @brief Set list of coding standards (checked by Cppcheck Premium). * @param codingStandards List of coding standards. */ void setCodingStandards(QStringList codingStandards) { mCodingStandards = std::move(codingStandards); } /** Cert C: int precision */ void setCertIntPrecision(int p) { mCertIntPrecision = p; } int getCertIntPrecision() const { return mCertIntPrecision; } /** Cppcheck Premium: License file */ void setLicenseFile(const QString& licenseFile) { mPremiumLicenseFile = licenseFile; } const QString& getLicenseFile() const { return mPremiumLicenseFile; } /** * @brief Write project file (to disk). * @param filename Filename to use. */ bool write(const QString &filename = QString()); /** * @brief Set filename for the project file. * @param filename Filename to use. */ void setFilename(const QString &filename) { mFilename = filename; } /** Do not only check how interface is used. Also check that interface is safe. */ class SafeChecks : public Settings::SafeChecks { public: SafeChecks() : Settings::SafeChecks() {} void loadFromXml(QXmlStreamReader &xmlReader); void saveToXml(QXmlStreamWriter &xmlWriter) const; }; SafeChecks safeChecks; /** Check unknown function return values */ const QStringList& getCheckUnknownFunctionReturn() const { return mCheckUnknownFunctionReturn; } /* void setCheckUnknownFunctionReturn(const QStringList &s) { mCheckUnknownFunctionReturn = s; } */ /** Use Clang parser */ bool clangParser; protected: /** * @brief Read optional root path from XML. * @param reader XML stream reader. */ void readRootPath(const QXmlStreamReader &reader); void readBuildDir(QXmlStreamReader &reader); /** * @brief Read importproject from XML. * @param reader XML stream reader. */ void readImportProject(QXmlStreamReader &reader); static bool readBool(QXmlStreamReader &reader); static int readInt(QXmlStreamReader &reader, int defaultValue); static QString readString(QXmlStreamReader &reader); /** * @brief Read list of include directories from XML. * @param reader XML stream reader. */ void readIncludeDirs(QXmlStreamReader &reader); /** * @brief Read list of defines from XML. * @param reader XML stream reader. */ void readDefines(QXmlStreamReader &reader); /** * @brief Read list paths to check. * @param reader XML stream reader. */ void readCheckPaths(QXmlStreamReader &reader); /** * @brief Read lists of excluded paths. * @param reader XML stream reader. */ void readExcludes(QXmlStreamReader &reader); /** * @brief Read lists of Visual Studio configurations * @param reader XML stream reader. */ void readVsConfigurations(QXmlStreamReader &reader); /** * @brief Read platform text. * @param reader XML stream reader. */ void readPlatform(QXmlStreamReader &reader); /** * @brief Read suppressions. * @param reader XML stream reader. */ void readSuppressions(QXmlStreamReader &reader); /** * @brief Read tag warnings, what warnings are tagged with a specific tag * @param reader XML stream reader. */ void readTagWarnings(QXmlStreamReader &reader, const QString &tag); /** * @brief Read string list * @param stringlist destination string list * @param reader XML stream reader * @param elementname elementname for each string */ static void readStringList(QStringList &stringlist, QXmlStreamReader &reader, const char elementname[]); /** * @brief Write string list * @param xmlWriter xml writer * @param stringlist string list to write * @param startelementname name of start element * @param stringelementname name of each string element */ static void writeStringList(QXmlStreamWriter &xmlWriter, const QStringList &stringlist, const char startelementname[], const char stringelementname[]); private: void clear(); /** * @brief Convert paths */ static QStringList fromNativeSeparators(const QStringList &paths); /** * @brief Filename (+path) of the project file. */ QString mFilename; /** * @brief Root path (optional) for the project. * This is the project root path. If it is present then all relative paths in * the project file are relative to this path. Otherwise paths are relative * to project file's path. */ QString mRootPath; /** Cppcheck build dir */ QString mBuildDir; /** Visual studio project/solution , compile database */ QString mImportProject; /** * Should all visual studio configurations be analyzed? * If this is false then only the Debug configuration * for the set platform is analyzed. */ bool mAnalyzeAllVsConfigs; /** Check only a selected VS configuration */ QStringList mVsConfigurations; /** Check code in headers */ bool mCheckHeaders; /** Check code in unused templates */ bool mCheckUnusedTemplates; /** * @brief Enable inline suppression. */ bool mInlineSuppression; /** * @brief List of include directories used to search include files. */ QStringList mIncludeDirs; /** * @brief List of defines. */ QStringList mDefines; /** * @brief List of undefines. */ QStringList mUndefines; /** * @brief List of paths to check. */ QStringList mPaths; /** * @brief Paths excluded from the check. */ QStringList mExcludedPaths; /** * @brief List of libraries. */ QStringList mLibraries; /** * @brief Platform */ QString mPlatform; /** * @brief List of suppressions. */ QList<SuppressionList::Suppression> mSuppressions; /** * @brief List of addons. */ QStringList mAddons; bool mBughunting = false; /** @brief Should Cppcheck run normal or exhaustive analysis? */ CheckLevel mCheckLevel = CheckLevel::normal; /** * @brief List of coding standards, checked by Cppcheck Premium. */ QStringList mCodingStandards; /** @brief Cppcheck Premium: license file */ QString mPremiumLicenseFile; /** @brief Project name, used when generating compliance report */ QString mProjectName; /** @brief Cppcheck Premium: This value is passed to the Cert C checker if that is enabled */ int mCertIntPrecision; /** @brief Execute clang analyzer? */ bool mClangAnalyzer; /** @brief Execute clang-tidy? */ bool mClangTidy; /** * @brief Tags */ QStringList mTags; /** * @brief Warning tags */ std::map<std::size_t, QString> mWarningTags; /** Max CTU depth */ int mMaxCtuDepth; /** Max template instantiation recursion */ int mMaxTemplateRecursion; QStringList mCheckUnknownFunctionReturn; static ProjectFile *mActiveProject; }; /// @} #endif // PROJECT_FILE_H
16,699
C++
.h
542
25.119926
186
0.662133
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,545
mainwindow.h
danmar_cppcheck/gui/mainwindow.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include "library.h" #include "platforms.h" #include <cstdint> #include <QFileDialog> #include <QMainWindow> #include <QObject> #include <QPair> #include <QString> #include <QStringList> class ThreadHandler; class TranslationHandler; class ScratchPad; class ProjectFile; class ApplicationList; class QAction; class QActionGroup; class QSettings; class QTimer; class QLineEdit; class ImportProject; class QCloseEvent; class QNetworkAccessManager; class QNetworkReply; class Settings; namespace Ui { class MainWindow; } /// @addtogroup GUI /// @{ /** * @brief Main window for cppcheck-gui * */ class MainWindow : public QMainWindow { Q_OBJECT public: /** * @brief Maximum number of MRU project items in File-menu. */ enum : std::uint8_t { MaxRecentProjects = 5 }; MainWindow(TranslationHandler* th, QSettings* settings); MainWindow(const MainWindow &) = delete; ~MainWindow() override; MainWindow &operator=(const MainWindow &) = delete; /** * List of checked platforms. */ Platforms mPlatforms; /** * @brief Analyze given code * * @param code Content of the (virtual) file to be analyzed * @param filename Name of the (virtual) file to be analyzed - determines language. */ void analyzeCode(const QString& code, const QString& filename); public slots: /** @brief Slot for analyze files menu item */ void analyzeFiles(); /** @brief Slot to reanalyze all files */ void reAnalyzeAll(); /** @brief Slot to reanalyze with checking library configuration */ void checkLibrary(); /** @brief Slot to check configuration */ void checkConfiguration(); /** * @brief Slot to reanalyze selected files * @param selectedFilesList list of selected files */ void performSelectedFilesCheck(const QStringList &selectedFilesList); /** @brief Slot to reanalyze modified files */ void reAnalyzeModified(); /** @brief Slot to clear all search results */ void clearResults(); /** @brief Slot to open XML report file */ void openResults(); /** * @brief Show errors with type "style" * @param checked Should errors be shown (true) or hidden (false) */ void showStyle(bool checked); /** * @brief Show errors with type "error" * @param checked Should errors be shown (true) or hidden (false) */ void showErrors(bool checked); /** * @brief Show errors with type "warning" * @param checked Should errors be shown (true) or hidden (false) */ void showWarnings(bool checked); /** * @brief Show errors with type "portability" * @param checked Should errors be shown (true) or hidden (false) */ void showPortability(bool checked); /** * @brief Show errors with type "performance" * @param checked Should errors be shown (true) or hidden (false) */ void showPerformance(bool checked); /** * @brief Show errors with type "information" * @param checked Should errors be shown (true) or hidden (false) */ void showInformation(bool checked); /** @brief Slot to check all "Show errors" menu items */ void checkAll(); /** @brief Slot to uncheck all "Show errors" menu items */ void uncheckAll(); /** @brief Slot for analyze directory menu item */ void analyzeDirectory(); /** @brief Slot to open program's settings dialog */ void programSettings(); /** @brief Slot to open program's about dialog */ void about(); /** @brief Slot to to show license text */ void showLicense(); /** @brief Slot to to show authors list */ void showAuthors(); /** @brief Slot to save results */ void save(); /** @brief Slot to generate compliance report */ void complianceReport(); /** @brief Slot to create new project file */ void newProjectFile(); /** @brief Slot to open project file and start analyzing contained paths. */ void openProjectFile(); /** @brief Slot to show scratchpad. */ void showScratchpad(); /** @brief Slot to close open project file. */ void closeProjectFile(); /** @brief Slot to edit project file. */ void editProjectFile(); /** @brief Slot for showing the scan and project statistics. */ void showStatistics(); /** @brief Slot for showing the library editor */ void showLibraryEditor(); private slots: /** @brief Slot for checkthread's done signal */ void analysisDone(); /** @brief Lock down UI while analyzing */ void checkLockDownUI(); /** @brief Slot for enabling save and clear button */ void resultsAdded(); /** @brief Slot for showing/hiding standard toolbar */ void toggleMainToolBar(); /** @brief Slot for showing/hiding Categories toolbar */ void toggleViewToolBar(); /** @brief Slot for showing/hiding Filter toolbar */ void toggleFilterToolBar(); /** @brief Slot for updating View-menu before it is shown. */ void aboutToShowViewMenu(); /** @brief Slot when stop analysis button is pressed */ void stopAnalysis(); /** @brief Open help file contents */ void openHelpContents(); /** @brief Filters the results in the result list. */ void filterResults(); /** @brief Opens recently opened project file. */ void openRecentProject(); /** @brief Selects the platform as analyzed platform. */ void selectPlatform(); /** Suppress error ids */ void suppressIds(QStringList ids); private slots: void replyFinished(QNetworkReply *reply); void hideInformation(); void changeReportType(); private: bool isCppcheckPremium() const; /** Get filename for last results */ QString getLastResults() const; /** @brief Reanalyzes files */ void reAnalyze(bool all); /** * @brief Reanalyze selected files * @param files list of selected files */ void reAnalyzeSelected(const QStringList& files); /** * @brief Analyze the project. * @param projectFile Pointer to the project to analyze. * @param recheckFiles files to recheck, empty => check all files * @param checkLibrary Flag to indicate if the library should be checked. * @param checkConfiguration Flag to indicate if the configuration should be checked. */ void analyzeProject(const ProjectFile *projectFile, const QStringList& recheckFiles, bool checkLibrary = false, bool checkConfiguration = false); /** * @brief Set current language * @param code Language code of the language to set (e.g. "en"). */ void setLanguage(const QString &code); /** @brief Event coming when application is about to close. */ void closeEvent(QCloseEvent *event) override; /** * @brief Helper function to toggle all show error menu items * @param checked Should all errors be shown (true) or hidden (false) */ void toggleAllChecked(bool checked); /** @brief Helper function to enable/disable all check,recheck buttons */ void enableCheckButtons(bool enable); /** @brief Helper function to enable/disable results buttons (clear,save,print) */ void enableResultsButtons(); /** * @brief Select files/or directory to analyze. * Helper function to open a dialog to ask user to select files or * directory to analyze. Use native dialogs instead of Qt:s own dialogs. * * @param mode Dialog open mode (files or directories) * @return QStringList of files or directories that were selected to analyze */ QStringList selectFilesToAnalyze(QFileDialog::FileMode mode); /** * @brief Analyze project * @param p imported project * @param checkLibrary Flag to indicate if library should be checked * @param checkConfiguration Flag to indicate if the configuration should be checked. */ void doAnalyzeProject(ImportProject p, bool checkLibrary = false, bool checkConfiguration = false); /** * @brief Analyze all files specified in parameter files * * @param files List of files and/or directories to analyze * @param checkLibrary Flag to indicate if library should be checked * @param checkConfiguration Flag to indicate if the configuration should be checked. */ void doAnalyzeFiles(const QStringList &files, bool checkLibrary = false, bool checkConfiguration = false); /** * @brief Get our default cppcheck settings and read project file. * * @return Default cppcheck settings */ QPair<bool, Settings> getCppcheckSettings(); /** @brief Load program settings */ void loadSettings(); /** @brief Save program settings */ void saveSettings() const; /** * @brief Format main window title. * @param text Text added to end of the title. */ void formatAndSetTitle(const QString &text = QString()); /** @brief Show help contents */ static void openOnlineHelp(); /** * @brief Enable or disable project file actions. * Project editing and closing actions should be only enabled when project is * open and we are not analyzing files. * @param enable If true then actions are enabled. */ void enableProjectActions(bool enable); /** * @brief Enable or disable project file actions. * Project opening and creating actions should be disabled when analyzing. * @param enable If true then actions are enabled. */ void enableProjectOpenActions(bool enable); /** * @brief Add include directories. * @param includeDirs List of include directories to add. * @param result Settings class where include directories are added. */ void addIncludeDirs(const QStringList &includeDirs, Settings &result); /** * @brief Handle command line parameters given to GUI. * @param params List of string given to command line. */ void handleCLIParams(const QStringList &params); /** * @brief Load XML file to the GUI. * @param selectedFile Filename (inc. path) of XML file to load. */ void loadResults(const QString &selectedFile); /** * @brief Load XML file to the GUI. * @param selectedFile Filename (inc. path) of XML file to load. * @param sourceDirectory Path to the directory that the results were generated for. */ void loadResults(const QString &selectedFile, const QString &sourceDirectory); /** * @brief Load last project results to the GUI. * @return Returns true if last results was loaded */ bool loadLastResults(); /** * @brief Load project file to the GUI. * @param filePath Filename (inc. path) of project file to load. */ void loadProjectFile(const QString &filePath); /** * @brief Load library file * @param library library to use * @param filename filename (no path) * @return error code */ Library::Error loadLibrary(Library &library, const QString &filename); /** * @brief Tries to load library file, prints message on error * @param library library to use * @param filename filename (no path) * @return True if no error */ bool tryLoadLibrary(Library &library, const QString& filename); QString loadAddon(Settings &settings, const QString &filesDir, const QString &pythonCmd, const QString& addon); /** * @brief Update project MRU items in File-menu. */ void updateMRUMenuItems(); /** * @brief Add project file (path) to the MRU list. * @param project Full path to the project file to add. */ void addProjectMRU(const QString &project); /** * @brief Remove project file (path) from the MRU list. * @param project Full path of the project file to remove. */ void removeProjectMRU(const QString &project); /** @brief Program settings */ QSettings *mSettings; /** @brief Thread to analyze files */ ThreadHandler *mThread; /** @brief List of user defined applications to open errors with */ ApplicationList *mApplications; /** @brief Class to handle translation changes */ TranslationHandler *mTranslation; /** @brief Class holding all UI components */ Ui::MainWindow *mUI; /** @brief Current analyzed directory. */ QString mCurrentDirectory; /** @brief Scratchpad. */ ScratchPad* mScratchPad{}; /** @brief Project (file). */ ProjectFile* mProjectFile{}; /** @brief Filter field in the Filter toolbar. */ QLineEdit* mLineEditFilter; /** @brief Timer to delay filtering while typing. */ QTimer* mFilterTimer; /** @brief GUI actions for selecting the analyzed platform. */ QActionGroup *mPlatformActions; /** @brief GUI actions for selecting the coding standard. */ QActionGroup *mCStandardActions, *mCppStandardActions; /** @brief GUI actions for selecting language. */ QActionGroup *mSelectLanguageActions; /** @brief GUI actions for selecting report. */ QActionGroup *mSelectReportActions; /** * @brief Are we exiting the cppcheck? * If this is true then the cppcheck is waiting for check threads to exit * so that the application can be closed. */ bool mExiting{}; /** @brief Set to true in case of loading log file. */ bool mIsLogfileLoaded{}; /** * @brief Project MRU menu actions. * List of MRU menu actions. Needs also to store the separator. */ QAction *mRecentProjectActs[MaxRecentProjects + 1]; QString mCppcheckCfgAbout; QString mCppcheckCfgProductName; QNetworkAccessManager *mNetworkAccessManager = nullptr; }; /// @} #endif // MAINWINDOW_H
14,540
C++
.h
384
32.833333
149
0.690895
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,546
settingsdialog.h
danmar_cppcheck/gui/settingsdialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SETTINGSDIALOG_H #define SETTINGSDIALOG_H #include <QDialog> #include <QObject> #include <QString> #include <Qt> class QSettings; class QWidget; class ApplicationList; class TranslationHandler; class CodeEditorStyle; class QCheckBox; namespace Ui { class Settings; } /// @addtogroup GUI /// @{ /** * @brief Settings dialog * */ class SettingsDialog : public QDialog { Q_OBJECT public: SettingsDialog(ApplicationList *list, TranslationHandler *translator, bool premium, QWidget *parent = nullptr); SettingsDialog(const SettingsDialog &) = delete; ~SettingsDialog() override; SettingsDialog &operator=(const SettingsDialog &) = delete; /** * @brief Save all values to QSettings * */ void saveSettingValues() const; /** * @brief Get checkbox value for mShowFullPath * * @return should full path of errors be shown in the tree */ bool showFullPath() const; /** * @brief Get checkbox value for mSaveFullPath * * @return should full path of files be saved when creating a report */ bool saveFullPath() const; /** * @brief Get checkbox value for mNoErrorsMessage * * @return Should "no errors message" be hidden */ bool showNoErrorsMessage() const; /** * @brief Get checkbox value for mShowIdColumn * * @return Should error id column be displayed */ bool showErrorId() const; /** * @brief Get checkbox value for mEnableInconclusive * * @return Should inconclusive column be displayed */ bool showInconclusive() const; /** * @brief Get checkbox value for mSaveAllErrors * * @return should all errors be saved to report */ bool saveAllErrors() const; protected slots: /** * @brief Slot for clicking OK. * */ void ok(); /** @brief Slot for validating input value in @c editPythonPath */ void validateEditPythonPath(); /** * @brief Slot for adding a new application to the list * */ void addApplication(); /** * @brief Slot for deleting an application from the list * */ void removeApplication(); /** * @brief Slot for modifying an application in the list * */ void editApplication(); /** * @brief Slot for making the selected application as the default (first) * */ void defaultApplication(); /** @brief Slot for browsing for the python binary */ void browsePythonPath(); /** @brief Slot for browsing for the clang binary */ void browseClangPath(); /** * @brief Browse for MISRA file */ void browseMisraFile(); /** * @brief Set Code Editor Style to Default */ void setCodeEditorStyleDefault(); /** * @brief Edit Custom Code Editor Style */ void editCodeEditorStyle(); protected: /** * @brief Clear all applications from the list and re insert them from mTempApplications * */ void populateApplicationList(); /** * @brief Load saved values * Loads dialog size and column widths. * */ void loadSettings(); /** * @brief Save settings * Save dialog size and column widths. */ void saveSettings() const; /** * @brief Save a single checkboxes value * * @param settings Pointer to Settings. * @param box checkbox to save * @param name name for QSettings to store the value */ static void saveCheckboxValue(QSettings *settings, const QCheckBox *box, const QString &name); /** * @brief Convert bool to Qt::CheckState * * @param yes value to convert * @return value converted to Qt::CheckState */ static Qt::CheckState boolToCheckState(bool yes); /** * @brief Converts Qt::CheckState to bool * * @param state Qt::CheckState to convert * @return converted value */ static bool checkStateToBool(Qt::CheckState state); /** * @brief Populate the translations list. */ void initTranslationsList(); /** * @brief Current Code Editor Style */ CodeEditorStyle *mCurrentStyle; /** * @brief List of applications user has specified * */ ApplicationList *mApplications; /** * @brief Temporary list of applications * This will be copied to actual list of applications (mApplications) * when user clicks ok. */ ApplicationList *mTempApplications; /** * @brief List of translations. * */ TranslationHandler *mTranslator; /** * @brief Dialog from UI designer * */ Ui::Settings *mUI; private: void manageStyleControls(); static constexpr int mLangCodeRole = Qt::UserRole; bool mPremium; }; /// @} #endif // SETTINGSDIALOG_H
5,687
C++
.h
208
22.269231
98
0.656555
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,548
translationhandler.h
danmar_cppcheck/gui/translationhandler.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TRANSLATIONHANDLER_H #define TRANSLATIONHANDLER_H #include <QList> #include <QObject> #include <QString> class QTranslator; /// @addtogroup GUI /// @{ /** * @brief Information for one translation. * */ struct TranslationInfo { /** * @brief Readable name for the translation (e.g. "English"). * */ QString mName; /** * @brief Filename for the translation. * */ QString mFilename; /** * @brief ISO 639 language code for the translation (e.g. "en"). * */ QString mCode; }; /** * @brief A class handling the available translations. * * This class contains a list of available translations. The class also keeps * track which translation is the currently active translation. * */ class TranslationHandler : QObject { Q_OBJECT public: explicit TranslationHandler(QObject *parent = nullptr); /** * @brief Get a list of available translations. * @return List of available translations. * */ const QList<TranslationInfo>& getTranslations() const { return mTranslations; } /** * @brief Set active translation. * @param code ISO 639 language code for new selected translation. * @return true if succeeds, false otherwise. * */ bool setLanguage(const QString &code); /** * @brief Get currently selected translation. * @return ISO 639 language code for current translation. * */ const QString& getCurrentLanguage() const; /** * @brief Get translation suggestion for the system. * This function checks the current system locale and determines which of * the available translations is best as current translation. If none of * the available translations is good then it returns English ("en"). * @return Suggested translation ISO 639 language code. * */ QString suggestLanguage() const; protected: /** * @brief Add new translation to list of available translations. * @param name Name of the translation ("English"). * @param filename Filename of the translation. * */ void addTranslation(const char *name, const char *filename); /** * @brief Find language in the list and return its index. * @param code ISO 639 language code. * @return Index at list, or -1 if not found. * */ int getLanguageIndexByCode(const QString &code) const; private: /** * @brief ISO 639 language code of the currently selected translation. * */ QString mCurrentLanguage; /** * @brief List of available translations. * */ QList<TranslationInfo> mTranslations; /** * @brief Translator class instance. * */ QTranslator* mTranslator{}; }; /// @} #endif // TRANSLATIONHANDLER_H
3,589
C++
.h
121
25.347107
77
0.682715
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
26,549
codeeditstylecontrols.h
danmar_cppcheck/gui/codeeditstylecontrols.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // widget subclass methodology derived from here: // https://stackoverflow.com/questions/18257281/qt-color-picker-widget/43871405#43871405 #ifndef CODEEDITORSTYLECONTROLS_H #define CODEEDITORSTYLECONTROLS_H #include <QColor> #include <QComboBox> #include <QFont> #include <QObject> #include <QPushButton> class QWidget; class SelectColorButton : public QPushButton { Q_OBJECT public: explicit SelectColorButton(QWidget* parent); void setColor(const QColor& color); const QColor& getColor(); signals: // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void colorChanged(const QColor& newColor); public slots: void updateColor(); void changeColor(); private: QColor mColor; }; class SelectFontWeightCombo : public QComboBox { Q_OBJECT public: explicit SelectFontWeightCombo(QWidget* parent); void setWeight(QFont::Weight weight); const QFont::Weight& getWeight(); signals: // NOLINTNEXTLINE(readability-inconsistent-declaration-parameter-name) - caused by generated MOC code void weightChanged(QFont::Weight newWeight); public slots: void updateWeight(); void changeWeight(int index); private: QFont::Weight mWeight = QFont::Normal; }; #endif //CODEEDITORSTYLECONTROLS_H
2,072
C++
.h
58
32.913793
105
0.76665
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,551
projectfiledialog.h
danmar_cppcheck/gui/projectfiledialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PROJECTFILE_DIALOG_H #define PROJECTFILE_DIALOG_H #include "suppressions.h" #include <QDialog> #include <QList> #include <QObject> #include <QString> #include <QStringList> class QModelIndex; class QWidget; namespace Ui { class ProjectFile; } /// @addtogroup GUI /// @{ class ProjectFile; /** * @brief A dialog for editing project file data. */ class ProjectFileDialog : public QDialog { Q_OBJECT public: explicit ProjectFileDialog(ProjectFile *projectFile, bool premium, QWidget *parent = nullptr); ~ProjectFileDialog() override; private: void loadFromProjectFile(const ProjectFile *projectFile); void saveToProjectFile(ProjectFile *projectFile) const; /** Enable and disable widgets in the 'Paths and Defines' tab */ void updatePathsAndDefines(); /** * @brief Return project root path from the dialog control. * @return Project root path. */ QString getRootPath() const; QStringList getProjectConfigurations() const; void setProjectConfigurations(const QStringList &configs); QString getImportProject() const; /** Get Cppcheck build dir */ QString getBuildDir() const; /** * @brief Return include paths from the dialog control. * @return List of include paths. */ QStringList getIncludePaths() const; /** * @brief Return define names from the dialog control. * @return List of define names. */ QStringList getDefines() const; /** * @brief Return undefine names from the dialog control. * @return List of undefine names. */ QStringList getUndefines() const; /** * @brief Return check paths from the dialog control. * @return List of check paths. */ QStringList getCheckPaths() const; /** * @brief Return excluded paths from the dialog control. * @return List of excluded paths. */ QStringList getExcludedPaths() const; /** * @brief Return selected libraries from the dialog control. * @return List of libraries. */ QStringList getLibraries() const; /** * @brief Return suppressions from the dialog control. * @return List of suppressions. */ const QList<SuppressionList::Suppression>& getSuppressions() const { return mSuppressions; } /** * @brief Set project root path to dialog control. * @param root Project root path to set to dialog control. */ void setRootPath(const QString &root); /** Set build dir */ void setBuildDir(const QString &buildDir); void setImportProject(const QString &importProject); /** * @brief Set include paths to dialog control. * @param includes List of include paths to set to dialog control. */ void setIncludepaths(const QStringList &includes); /** * @brief Set define names to dialog control. * @param defines List of define names to set to dialog control. */ void setDefines(const QStringList &defines); /** * @brief Set undefine names to dialog control. * @param undefines List of undefine names to set to dialog control. */ void setUndefines(const QStringList &undefines); /** * @brief Set check paths to dialog control. * @param paths List of path names to set to dialog control. */ void setCheckPaths(const QStringList &paths); /** * @brief Set excluded paths to dialog control. * @param paths List of path names to set to dialog control. */ void setExcludedPaths(const QStringList &paths); /** * @brief Set libraries to dialog control. * @param libraries List of libraries to set to dialog control. */ void setLibraries(const QStringList &libraries); /** * @brief Add a single suppression to dialog control. * @param suppression A suppressions to add to dialog control. */ void addSingleSuppression(const SuppressionList::Suppression &suppression); /** * @brief Set suppressions to dialog control. * @param suppressions List of suppressions to set to dialog control. */ void setSuppressions(const QList<SuppressionList::Suppression> &suppressions); private slots: /** ok button pressed, save changes and accept */ void ok(); /** * @brief Browse for build dir. */ void browseBuildDir(); /** * @brief Clear 'import project'. */ void clearImportProject(); /** * @brief Browse for solution / project / compile database. */ void browseImportProject(); /** * @brief Add new path to check. */ void addCheckPath(); /** * @brief Edit path in the list. */ void editCheckPath(); /** * @brief Remove path from the list. */ void removeCheckPath(); /** * @brief Browse for include directory. * Allow user to add new include directory to the list. */ void addIncludeDir(); /** * @brief Remove include directory from the list. */ void removeIncludeDir(); /** * @brief Edit include directory in the list. */ void editIncludeDir(); /** * @brief Add new path to exclude list. */ void addExcludePath(); /** * @brief Add new file to exclude list. */ void addExcludeFile(); /** * @brief Edit excluded path in the list. */ void editExcludePath(); /** * @brief Remove excluded path from the list. */ void removeExcludePath(); /** * @brief Move include path up in the list. */ void moveIncludePathUp(); /** * @brief Move include path down in the list. */ void moveIncludePathDown(); /** * @brief Add suppression to the list */ void addSuppression(); /** * @brief Remove selected suppression from the list */ void removeSuppression(); /** * @brief Edit suppression (double clicking on suppression) */ void editSuppression(const QModelIndex &index); /** * @brief Browse for misra file */ void browseMisraFile(); /** * @brief Check for all VS configurations */ void checkAllVSConfigs(); /** @brief Browse for Cppcheck Premium license file */ void browseLicenseFile(); protected: /** * @brief Save dialog settings. */ void loadSettings(); /** * @brief Load dialog settings. */ void saveSettings() const; /** * @brief Add new indlude directory. * @param dir Directory to add. */ void addIncludeDir(const QString &dir); /** * @brief Add new path to check. * @param path Path to add. */ void addCheckPath(const QString &path); /** * @brief Add new path to ignore list. * @param path Path to add. */ void addExcludePath(const QString &path); /** * @brief Get mSuppressions index that match the * given short text * @param shortText text as generated by Suppression::getText * @return index of matching suppression, -1 if not found */ int getSuppressionIndex(const QString &shortText) const; private: static QStringList getProjectConfigs(const QString &fileName); Ui::ProjectFile * const mUI; /** * @brief Projectfile path. */ ProjectFile * const mProjectFile; /** Is this Cppcheck Premium? */ const bool mPremium; QString getExistingDirectory(const QString &caption, bool trailingSlash); QList<SuppressionList::Suppression> mSuppressions; }; /// @} #endif // PROJECTFILE_DIALOG_H
8,355
C++
.h
272
25.617647
98
0.668954
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,552
csvreport.h
danmar_cppcheck/gui/csvreport.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef CSV_REPORT_H #define CSV_REPORT_H #include "report.h" #include <QString> #include <QTextStream> class ErrorItem; /// @addtogroup GUI /// @{ /** * @brief CSV text file report. * This report exports results as CSV (comma separated values). CSV files are * easy to import to many other programs. * @todo This class should be inherited from TxtReport? */ class CsvReport : public Report { public: explicit CsvReport(const QString &filename); /** * @brief Create the report (file). * @return true if succeeded, false if file could not be created. */ bool create() override; /** * @brief Write report header. */ void writeHeader() override; /** * @brief Write report footer. */ void writeFooter() override; /** * @brief Write error to report. * @param error Error data. */ void writeError(const ErrorItem &error) override; private: /** * @brief Text stream writer for writing the report in text format. */ QTextStream mTxtWriter; }; /// @} #endif // CSV_REPORT_H
1,849
C++
.h
60
27.516667
77
0.699324
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,553
statsdialog.h
danmar_cppcheck/gui/statsdialog.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef STATSDIALOG_H #define STATSDIALOG_H #include <QDialog> #include <QObject> #include <QString> class ProjectFile; class CheckStatistics; class QWidget; namespace Ui { class StatsDialog; } /// @addtogroup GUI /// @{ /** * @brief A dialog that shows project and scan statistics. * */ class StatsDialog : public QDialog { Q_OBJECT public: explicit StatsDialog(QWidget *parent = nullptr); ~StatsDialog() override; /** * @brief Sets the project to extract statistics from */ void setProject(const ProjectFile *projectFile); /** * @brief Sets the string to display beside "Path Selected:" */ void setPathSelected(const QString& path); /** * @brief Sets the number to display beside "Number of Files Scanned:" */ void setNumberOfFilesScanned(int num); /** * @brief Sets the number of seconds to display beside "Scan Duration:" */ void setScanDuration(double seconds); /** * @brief Sets the numbers of different error/warnings found." */ void setStatistics(const CheckStatistics *stats); private slots: void copyToClipboard(); void pdfExport(); private: Ui::StatsDialog *mUI; const CheckStatistics* mStatistics{}; }; /// @} #endif // STATSDIALOG_H
2,046
C++
.h
68
26.823529
75
0.714504
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,554
testfilelist.h
danmar_cppcheck/gui/test/filelist/testfilelist.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2021 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QObject> #include <QString> class TestFileList : public QObject { Q_OBJECT private slots: void addFile() const; void addPathList() const; void addFile_notexist() const; void addFile_unknown() const; void addDirectory() const; void addDirectory_recursive() const; void filterFiles() const; void filterFiles2() const; void filterFiles3() const; void filterFiles4() const; void filterFiles5() const; };
1,223
C++
.h
34
33
72
0.731872
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,555
testresultstree.h
danmar_cppcheck/gui/test/resultstree/testresultstree.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2021 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QObject> class TestResultsTree : public QObject { Q_OBJECT private slots: void test1() const; void testReportType() const; void testGetGuidelineError() const; };
953
C++
.h
25
35.72
72
0.741622
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,556
testprojectfile.h
danmar_cppcheck/gui/test/projectfile/testprojectfile.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2021 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QObject> class TestProjectFile : public QObject { Q_OBJECT private slots: void loadInexisting() const; void loadSimple() const; void loadSimpleWithIgnore() const; void loadSimpleNoroot() const; void getAddonFilePath() const; void getInlineSuppressionDefaultValue() const; void getInlineSuppression() const; void getCheckingSuppressionsRelative() const; void getCheckingSuppressionsAbsolute() const; void getCheckingSuppressionsStar() const; };
1,266
C++
.h
32
36.5
72
0.754072
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,557
testcppchecklibrarydata.h
danmar_cppcheck/gui/test/cppchecklibrarydata/testcppchecklibrarydata.h
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2021 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "cppchecklibrarydata.h" #include <QObject> #include <QString> class TestCppcheckLibraryData : public QObject { Q_OBJECT private slots: void init(); void xmlReaderError(); void unhandledElement(); void mandatoryAttributeMissing(); void podtypeValid(); void typechecksValid(); void smartPointerValid(); void platformTypeValid(); void memoryResourceValid(); void defineValid(); void undefineValid(); void reflectionValid(); void markupValid(); void containerValid(); void validateAllCfg(); private: static void loadCfgFile(const QString &filename, CppcheckLibraryData &data, QString &res, bool removeFile = false); static void saveCfgFile(const QString &filename, CppcheckLibraryData &data); CppcheckLibraryData libraryData; CppcheckLibraryData fileLibraryData; QString result; static const QString TempCfgFile; };
1,681
C++
.h
46
33.065217
119
0.747692
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,573
sfm_data_triangulation_test.cpp
openMVG_openMVG/src/openMVG/sfm/sfm_data_triangulation_test.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2018 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //----------------- // Test summary: //----------------- // - Test sfm_data track triangulation //----------------- #include "openMVG/sfm/pipelines/pipelines_test.hpp" #include "openMVG/sfm/sfm_data_triangulation.hpp" #include "testing/testing.h" using namespace openMVG; using namespace openMVG::sfm; TEST(SFM_DATA_TRIANGULATION, BLIND) { const int nviews = 6; const int npoints = 32; const nViewDatasetConfigurator config; const NViewDataSet d = NRealisticCamerasRing(nviews, npoints, config); // Translate the input dataset to a SfM_Data scene const SfM_Data sfm_data = getInputScene(d, config, cameras::PINHOLE_CAMERA); // Remove poses and structure SfM_Data sfm_data_2 = sfm_data; // Set fake data for landmark position for (auto& obs: sfm_data_2.structure) { obs.second.X.fill(0); } // Test the blind triangulation engine SfM_Data_Structure_Computation_Blind triangulation_engine; // Triangulate the landmarks and look if the 3D point are recovered { triangulation_engine.triangulate(sfm_data_2); EXPECT_EQ(npoints, sfm_data_2.structure.size()); for (const auto& obs: sfm_data_2.structure) { EXPECT_MATRIX_NEAR(sfm_data.structure.at(obs.first).X, obs.second.X, 1e-8); } } // A landmark with empty information should be removed by the triangulation engine sfm_data_2.structure[0].obs.clear(); { triangulation_engine.triangulate(sfm_data_2); EXPECT_EQ(npoints - 1, sfm_data_2.structure.size()); } } TEST(SFM_DATA_TRIANGULATION, ROBUST) { const int nviews = 6; const int npoints = 32; const nViewDatasetConfigurator config; const NViewDataSet d = NRealisticCamerasRing(nviews, npoints, config); // Translate the input dataset to a SfM_Data scene const SfM_Data sfm_data = getInputScene(d, config, cameras::PINHOLE_CAMERA); // Remove poses and structure SfM_Data sfm_data_2 = sfm_data; // Set fake data for landmark position for (auto& obs: sfm_data_2.structure) { obs.second.X.fill(0); } // Test the robust triangulation engine SfM_Data_Structure_Computation_Robust triangulation_engine; // Triangulate the landmarks and look if the 3D point are recovered { triangulation_engine.triangulate(sfm_data_2); EXPECT_EQ(npoints, sfm_data_2.structure.size()); for (const auto& obs: sfm_data_2.structure) { EXPECT_MATRIX_NEAR(sfm_data.structure.at(obs.first).X, obs.second.X, 1e-8); } } // A landmark with empty information should be removed by the triangulation engine sfm_data_2.structure[0].obs.clear(); { triangulation_engine.triangulate(sfm_data_2); EXPECT_EQ(npoints - 1, sfm_data_2.structure.size()); } // A landmark with an outlier should still be there if triangulable sfm_data_2.structure.clear(); sfm_data_2.structure[0] = sfm_data.structure.at(0); { sfm_data_2.structure[0].obs[0].x += Vec2(-10, -10000); sfm_data_2.structure[0].obs[1].x += Vec2(-10000, -10000); triangulation_engine.triangulate(sfm_data_2); EXPECT_EQ(1, sfm_data_2.structure.size()); } } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */
3,616
C++
.cpp
91
36.428571
84
0.683805
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
26,596
sfm_stellar_engine.cpp
openMVG_openMVG/src/openMVG/sfm/pipelines/stellar/sfm_stellar_engine.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/sfm/pipelines/stellar/sfm_stellar_engine.hpp" #include "openMVG/cameras/Camera_Common.hpp" #include "openMVG/features/feature.hpp" #include "openMVG/graph/graph.hpp" #include "openMVG/graph/triplet_finder.hpp" #include "openMVG/multiview/essential.hpp" #include "openMVG/multiview/translation_averaging_common.hpp" #include "openMVG/multiview/translation_averaging_solver.hpp" #include "openMVG/multiview/triangulation.hpp" #include "openMVG/sfm/sfm_data_filters.hpp" #include "openMVG/sfm/pipelines/global/sfm_global_reindex.hpp" #include "openMVG/sfm/pipelines/relative_pose_engine.hpp" #include "openMVG/sfm/pipelines/sfm_features_provider.hpp" #include "openMVG/sfm/pipelines/sfm_matches_provider.hpp" #include "openMVG/sfm/pipelines/sfm_robust_model_estimation.hpp" #include "openMVG/sfm/pipelines/stellar/stellar_definitions.hpp" #include "openMVG/sfm/pipelines/stellar/stellar_solver.hpp" #include "openMVG/sfm/sfm_data_BA_ceres.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/sfm/sfm_data_triangulation.hpp" #include "openMVG/system/loggerprogress.hpp" #include "openMVG/system/timer.hpp" #include "third_party/histogram/histogram.hpp" #include "third_party/htmlDoc/htmlDoc.hpp" #include <ceres/types.h> #include "lemon/kruskal.h" namespace openMVG{ namespace sfm{ using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::features; StellarSfMReconstructionEngine::StellarSfMReconstructionEngine( const SfM_Data & sfm_data, const std::string & out_directory_logging, const std::string & logging_file) : ReconstructionEngine(sfm_data, out_directory_logging), html_doc_stream_(nullptr), logging_file_(logging_file), features_provider_(nullptr), matches_provider_(nullptr), graph_simplification_(EGraphSimplification::MST_X), graph_simplification_value_(5) { if (!logging_file_.empty()) { // setup HTML logger html_doc_stream_ = std::make_shared<htmlDocument::htmlDocumentStream>("Stellar SFM report."); html_doc_stream_->pushInfo( htmlDocument::htmlMarkup("h1", std::string("StellarSfMReconstructionEngine"))); html_doc_stream_->pushInfo("<hr>"); html_doc_stream_->pushInfo( "Dataset info:"); html_doc_stream_->pushInfo( "Views count: " + htmlDocument::toString( sfm_data.GetViews().size()) + "<br>"); } } StellarSfMReconstructionEngine::~StellarSfMReconstructionEngine() { if (!logging_file_.empty()) { // Save the reconstruction Log std::ofstream htmlFileStream(logging_file_.c_str()); htmlFileStream << html_doc_stream_->getDoc(); } } void StellarSfMReconstructionEngine::SetFeaturesProvider( Features_Provider * provider) { features_provider_ = provider; } void StellarSfMReconstructionEngine::SetMatchesProvider( Matches_Provider * provider) { matches_provider_ = provider; } void StellarSfMReconstructionEngine::SetGraphSimplification ( const EGraphSimplification graph_simplification, const int value ) { graph_simplification_ = graph_simplification; graph_simplification_value_ = value; } bool StellarSfMReconstructionEngine::Process() { // Compute a relative pose for each pair Hash_Map<Pair, geometry::Pose3> relative_poses; ComputeRelativeMotions(relative_poses); // From the found relative motion, compute the stellar/nuplet reconstructions Hash_Map<IndexT, StellarPodRelativeMotions> stellar_reconstruction_per_pose; if (!ComputeStellarReconstructions(relative_poses, stellar_reconstruction_per_pose)) return false; OPENMVG_LOG_INFO << "#Stellar reconstruction pod: " << stellar_reconstruction_per_pose.size(); // Perform the rotation averaging and compute the global rotations //a- extract largest CC first openMVG::rotation_averaging::RelativeRotations relatives_R; Pair_Set pairs; std::set<IndexT> base_nodes; for (const auto & pod_it : stellar_reconstruction_per_pose) { for (const auto & rel_it : pod_it.second.relative_motions) { pairs.insert({rel_it.first.first, rel_it.first.second}); base_nodes.insert(rel_it.first.first); base_nodes.insert(rel_it.first.second); } } const auto largest_cc_nodes = graph::KeepLargestCC_Nodes<Pair_Set, IndexT>(pairs); OPENMVG_LOG_INFO << "Largest CC => Keeping " << largest_cc_nodes.size() << " nodes from " << base_nodes.size() << " base nodes"; for (const auto & pod_it : stellar_reconstruction_per_pose) { for (const auto & rel_it : pod_it.second.relative_motions) { if(largest_cc_nodes.count(rel_it.first.first) && largest_cc_nodes.count(rel_it.first.second)) { relatives_R.emplace_back( rel_it.first.first, rel_it.first.second, // {i,j} rel_it.second.rotation, // R_ij, the relative rotation 1.0); // Weight } } } //b- the rotation averaging step Hash_Map<IndexT, Mat3> global_rotations; Pair_Set selected_pairs; if (!Compute_Global_Rotations(relatives_R, global_rotations, selected_pairs)) { OPENMVG_LOG_ERROR << "GlobalSfM:: Rotation Averaging failure!"; return false; } // Perform the translation averaging and compute the global positions //a- be sure rotation averaging has not disconnected the graph { const auto largest_cc_nodes_rot = graph::KeepLargestCC_Nodes<Pair_Set, IndexT>(selected_pairs); assert(largest_cc_nodes_rot.size() == global_rotations.size()); //b- translation averaging step if (!Compute_Global_Translations(global_rotations, selected_pairs, stellar_reconstruction_per_pose)) { OPENMVG_LOG_ERROR << "GlobalSfM:: Translation Averaging failure!"; return false; } } // Perform point triangulation and bundle adjust scene { const int min_covisibility = 2; if (!Compute_Initial_Structure(min_covisibility)) { OPENMVG_LOG_ERROR << "GlobalSfM:: Cannot initialize an initial structure!"; return false; } if (!Adjust()) { OPENMVG_LOG_ERROR << "GlobalSfM:: Non-linear adjustment failure!"; return false; } } return true; } Pair_Set selectMST(const openMVG::matching::PairWiseMatches & matches, const int nbTree) { Pair_Set selected_pairs; // Build a graph, affect edge weight depending of supporting match // Do N time : select an MST (set weight to 0) // return the supporting edges graph::indexedGraph graph_builder(getPairs(matches)); using map_EdgeMap = graph::indexedGraph::GraphT::EdgeMap<double>; map_EdgeMap edge_map(graph_builder.g); using EdgeIterator = graph::indexedGraph::GraphT::EdgeIt; for ( EdgeIterator it( graph_builder.g ); it != lemon::INVALID; ++it ) { const auto & found = matches.at(std::make_pair( (*graph_builder.node_map_id)[graph_builder.g.u(it)], (*graph_builder.node_map_id)[graph_builder.g.v(it)])); edge_map[it] = - static_cast<double>(found.size()); } int nb_select = nbTree; // Select Many MST while (nb_select>0) { std::vector<graph::indexedGraph::GraphT::Edge> tree_edge_vec; lemon::kruskal(graph_builder.g, edge_map, std::back_inserter(tree_edge_vec)); //E-- Export compute MST for (const auto & edge_it : tree_edge_vec ) { selected_pairs.insert( {(*graph_builder.node_map_id)[graph_builder.g.u(edge_it)], (*graph_builder.node_map_id)[graph_builder.g.v(edge_it)]}); // Update the weight to avoid resampling the same tree next time edge_map[edge_it] = 0; } --nb_select; } OPENMVG_LOG_INFO << "Graph simplification:\n" <<"\tUsing #trees: " << nbTree << " selected #pairs: " << selected_pairs.size() << "\n" <<"\tOriginal graph #pairs: " << matches.size() << "\n" <<"\tKeep: " << selected_pairs.size() / (float)matches.size() << " % of original graph."; return selected_pairs; } void StellarSfMReconstructionEngine::ComputeRelativeMotions( Hash_Map<Pair, Pose3> & relative_poses ) const { /// If there is a JSON cache use it: /*if (stlplus::is_file(sOut_directory_ + "/relative_motion_cache")) { std::ifstream stream((sOut_directory_ + "/relative_motion_cache").c_str()); cereal::JSONInputArchive archive(stream); archive(relative_poses); std::cout << "\n::Compute_Relative_Motions\n" << "Loaded #RelativePoses: " << relative_poses.size() << std::endl; return; }*/ Pair_Set selected_pairs; switch (graph_simplification_) { case EGraphSimplification::NONE: { // No simplification selected_pairs = matching::getPairs(matches_provider_->pairWise_matches_); } break; case EGraphSimplification::STAR_X: // Keep the X edges per n-Uplet { // Limit the complexity of each sub-star int max_stellar_pod_size = graph_simplification_value_; // 10 const Pair_Set pairs = matching::getPairs(matches_provider_->pairWise_matches_); // Enhance the selected pairs in order to ensure that each NUplets have at maximum max_stellar_pod_size edges { // List all stellar configurations using StellarPods = Hash_Map<IndexT, Pair_Set>; StellarPods stellar_pods; for (const auto & it : pairs) { const Pair & pairIt = it; stellar_pods[pairIt.first].insert(pairIt); stellar_pods[pairIt.second].insert(pairIt); } // Keep only the Nth best pairs for each node for (auto & stellar_pod_it : stellar_pods) { Pair_Set & pairs = stellar_pod_it.second; unsigned int count = 0; std::vector<std::pair<unsigned int, unsigned int> > matches_per_edges; for (const Pair & pair_it : pairs) { matches_per_edges.emplace_back(matches_provider_->pairWise_matches_.at(pair_it).size(), count++); } std::sort(matches_per_edges.begin(), matches_per_edges.end()); Pair_Set cpy; for ( std::vector<std::pair<unsigned int, unsigned int> >::const_reverse_iterator iter = matches_per_edges.rbegin(); iter != matches_per_edges.rend() && cpy.size() < max_stellar_pod_size; ++ iter) { const unsigned int offset = iter->second; Pair_Set::const_iterator iterP = pairs.begin(); std::advance(iterP, offset); cpy.insert(*iterP); selected_pairs.insert(*iterP); } } } // In order to guarantee the same connectivity as the initial graph, we add a MST to the pairs const int nb_trees = 1; const auto mst_pairs = selectMST(matches_provider_->pairWise_matches_, nb_trees); selected_pairs.insert(mst_pairs.begin(), mst_pairs.end()); } break; case EGraphSimplification::MST_X: { // Select X random MST const int nb_trees = graph_simplification_value_; //Note: nb_trees could be dynamic depending of the node degree (median) selected_pairs = selectMST(matches_provider_->pairWise_matches_, nb_trees); } break; default: OPENMVG_LOG_ERROR << "Unknown graph simplification method"; break; } OPENMVG_LOG_INFO << "Initial graph got: " << matches_provider_->pairWise_matches_.size() << " view pairs \n" << "\t Will use: " << selected_pairs.size() << " relative pose pairs."; // Compute a relative pose for each edge of the pose pair graph relative_poses = [&] { Relative_Pose_Engine relative_pose_engine; if (!relative_pose_engine.Process( selected_pairs, sfm_data_, matches_provider_, features_provider_)) return Relative_Pose_Engine::Relative_Pair_Poses(); else return relative_pose_engine.Get_Relative_Poses(); }(); /// Export to a JSON cache (for the relative motions): /* { std::ofstream stream((sOut_directory_ + "/relative_motion_cache").c_str()); cereal::JSONOutputArchive archive(stream); archive(relative_poses); } */ } bool StellarSfMReconstructionEngine::ComputeStellarReconstructions ( const Hash_Map<Pair, geometry::Pose3> & relative_poses, Hash_Map<IndexT, StellarPodRelativeMotions > & stellar_reconstruction_per_pose ) const { // List all stellar configurations using StellarPods = Hash_Map<IndexT, Pair_Set>; StellarPods stellar_pods; for (const auto & it : relative_poses) { const Pair & pairIt = it.first; stellar_pods[pairIt.first].insert(pairIt); stellar_pods[pairIt.second].insert(pairIt); } system::Timer t; OPENMVG_LOG_INFO << "::Compute_Stellar_Reconstructions - " << "#" << stellar_pods.size() << " pods." ; // Compute the local reconstruction of the pods and save their relative pose motions system::LoggerProgress my_progress_bar( stellar_pods.size(), "- Stellar pod reconstruction -" ); #ifdef OPENMVG_USE_OPENMP #pragma omp parallel for schedule(dynamic) #endif for (int stellar_it = 0; stellar_it < static_cast<int>(stellar_pods.size()); ++stellar_it) { #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif ++my_progress_bar; auto stellar_pod_it = stellar_pods.cbegin(); std::advance(stellar_pod_it, stellar_it); const IndexT node_id = stellar_pod_it->first; const Pair_Set & pairs = stellar_pod_it->second; const bool use_all_matches = false; const bool use_threading = false; Stellar_Solver stellar_pod_solver( pairs, relative_poses, sfm_data_, matches_provider_, features_provider_, use_all_matches, use_threading); Poses poses; if (!stellar_pod_solver.Solve(poses)) { OPENMVG_LOG_WARNING << "Cannot solve this Stellar pod"; continue; } #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { // Update the relative motions for this pod for (const auto pair_it : pairs) { const int I = pair_it.first; const int J = pair_it.second; Mat3 R_refined; Vec3 t_refined; RelativeCameraMotion( poses[I].rotation(), poses[I].translation(), poses[J].rotation(), poses[J].translation(), &R_refined, &t_refined); stellar_reconstruction_per_pose[node_id].relative_motions.insert( {pair_it, {R_refined, t_refined}}); } } } OPENMVG_LOG_INFO << "Stellar pods Relative motions computation took: " << t.elapsed() << " (s)"; return true; } bool StellarSfMReconstructionEngine::Compute_Global_Rotations ( const rotation_averaging::RelativeRotations & relatives_R, Hash_Map<IndexT, Mat3> & global_rotations, Pair_Set & used_pairs ) const { if (relatives_R.empty()) return false; // Log statistics about the relative rotation graph { std::set<IndexT> set_pose_ids; for (const auto & relative_R : relatives_R) { set_pose_ids.insert(relative_R.i); set_pose_ids.insert(relative_R.j); } OPENMVG_LOG_INFO << "-------------------------------" << "\n" << " Global rotations computation: " << "\n" << " #relative rotations: " << relatives_R.size() << "\n" << " #global rotations: " << set_pose_ids.size(); } // Global Rotation solver: const ERelativeRotationInferenceMethod eRelativeRotationInferenceMethod = //TRIPLET_ROTATION_INFERENCE_COMPOSITION_ERROR; TRIPLET_ROTATION_INFERENCE_NONE; system::Timer timer; GlobalSfM_Rotation_AveragingSolver rotation_averaging_solver; const bool b_rotation_averaging = rotation_averaging_solver.Run( ROTATION_AVERAGING_L2, eRelativeRotationInferenceMethod, relatives_R, global_rotations); OPENMVG_LOG_INFO << "Found #global_rotations: " << global_rotations.size() << "\n" << "in " << timer.elapsed() << " seconds."; if (b_rotation_averaging) { used_pairs = rotation_averaging_solver.GetUsedPairs(); // Compute fitting error std::vector<float> vec_rotation_fitting_error; vec_rotation_fitting_error.reserve(relatives_R.size()); for (const auto & relative_R : relatives_R) { const Mat3 & Rij = relative_R.Rij; const IndexT i = relative_R.i; const IndexT j = relative_R.j; if (global_rotations.count(i)==0 || global_rotations.count(j)==0) continue; const Mat3 & Ri = global_rotations[i]; const Mat3 & Rj = global_rotations[j]; const Mat3 eRij(Rj.transpose()*Rij*Ri); const double angularErrorDegree = R2D(getRotationMagnitude(eRij)); vec_rotation_fitting_error.push_back(angularErrorDegree); } // TODO list inliers/outlier with a boolean array // Export those pairs to see the problem // Check if a pair iS marked many time (since it can be listed many time) // Display some statistics about the relative to global rotation fitting estimation if (!vec_rotation_fitting_error.empty()) { Histogram<float> histo(0.0f, *max_element(vec_rotation_fitting_error.cbegin(), vec_rotation_fitting_error.cend()), 20); histo.Add(vec_rotation_fitting_error.cbegin(), vec_rotation_fitting_error.cend()); OPENMVG_LOG_INFO << "Relative rotations fitting error to global rotations:" << histo.ToString(); { Histogram<float> histo(0.0f, 5.0f, 20); histo.Add(vec_rotation_fitting_error.cbegin(), vec_rotation_fitting_error.cend()); OPENMVG_LOG_INFO << "Relative rotations fitting error to global rotations {0,5}:" << histo.ToString(); } OPENMVG_LOG_INFO << "Statistics about global rotation fitting:"; minMaxMeanMedian<float>(vec_rotation_fitting_error.cbegin(), vec_rotation_fitting_error.cend(), std::cout); } // Log input graph to the HTML report if (!logging_file_.empty() && !sOut_directory_.empty()) { // Log a relative pose graph { std::set<IndexT> set_pose_ids; Pair_Set relative_pose_pairs; for (const auto & view : sfm_data_.GetViews()) { const IndexT pose_id = view.second->id_pose; set_pose_ids.insert(pose_id); } const std::string sGraph_name = "global_relative_rotation_pose_graph_final"; graph::indexedGraph putativeGraph(set_pose_ids, rotation_averaging_solver.GetUsedPairs()); graph::exportToGraphvizData( stlplus::create_filespec(sOut_directory_, sGraph_name), putativeGraph); using namespace htmlDocument; std::ostringstream os; os << "<br>" << sGraph_name << "<br>" << "<img src=\"" << stlplus::create_filespec(sOut_directory_, sGraph_name, "svg") << "\" height=\"600\">\n"; html_doc_stream_->pushInfo(os.str()); } } } return b_rotation_averaging; } /// Compute global translations bool StellarSfMReconstructionEngine::Compute_Global_Translations ( const Hash_Map<IndexT, Mat3> & global_rotations, const Pair_Set & used_pairs, const Hash_Map<IndexT, StellarPodRelativeMotions> & stellar_reconstruction_per_pose ) { // Collect the relative motions between valid image pairs: // pairs belonging to a stellar reconstruction and for which global rotations has been estimated Pair_Set valid_pairs; std::vector<RelativeInfo_Vec> stellar_relative_motions; std::set<IndexT> poses_ids; IndexT relative_motion_count = 0; { for (const auto & stellar_pod_it : stellar_reconstruction_per_pose) { const IndexT node_id = stellar_pod_it.first; if (global_rotations.count(node_id) == 0) continue; RelativeInfo_Vec relative_motion_infos; for (const auto & relative_info_it : stellar_pod_it.second.relative_motions) { const IndexT i = relative_info_it.first.first; const IndexT j = relative_info_it.first.second; if (global_rotations.count(i)==0 || global_rotations.count(j)==0 || used_pairs.count(relative_info_it.first) == 0) continue; valid_pairs.insert({i,j}); poses_ids.insert(i); poses_ids.insert(j); // update the relative rotation to use global rotations const Mat3 & Ri = global_rotations.at(i); const Mat3 & Rj = global_rotations.at(j); const Mat3 relative_rotation = Rj * Ri.transpose(); relative_motion_infos.emplace_back( relative_info_it.first, std::make_pair(relative_rotation, relative_info_it.second.translation)); } if (!relative_motion_infos.empty()) { relative_motion_count += relative_motion_infos.size(); stellar_relative_motions.push_back(relative_motion_infos); } } } const size_t iNview = poses_ids.size(); OPENMVG_LOG_INFO << "-------------------------------" << "\n" << " Global translations computation: " << "\n" << " - Ready to compute " << iNview << " global translations." << "\n" << " from #relative translations: " << relative_motion_count; openMVG::system::Timer timer_translation; // Re-index the pair pose indices for solving the translations // Build a mapping from the native index to a contiguous sequence Hash_Map<IndexT, IndexT> reindex_forward, reindex_backward; reindex(valid_pairs, reindex_forward, reindex_backward); for (auto & stellar_group_it : stellar_relative_motions) { for (auto & relative_motion_it : stellar_group_it) { const auto & i = relative_motion_it.first.first; const auto & j = relative_motion_it.first.second; // reindex the pose ids relative_motion_it.first = {reindex_forward[i], reindex_forward[j]}; } } std::vector<Vec3> vec_translations; if (!solve_translations_problem_softl1(stellar_relative_motions, vec_translations)) { OPENMVG_LOG_ERROR << "Compute global translations: failed"; return false; } //-- Export statistics: { std::ostringstream os; os << "Translation averaging statistics."; os.str(""); os << "-------------------------------" << "\n" << "-- #relative estimates: " << relative_motion_count << "\n" << "-- #global translations: " << vec_translations.size() << "\n" << " timing (s): " << timer_translation << ".\n" << "-------------------------------" << "\n"; OPENMVG_LOG_INFO << os.str(); } // A valid solution was found: // - Update the view poses according the found camera translations for (size_t i = 0; i < vec_translations.size(); ++i) { const Vec3 & t = vec_translations[i]; const IndexT pose_id = reindex_backward.at(i); const Mat3 & Ri = global_rotations.at(pose_id); sfm_data_.poses[pose_id] = Pose3(Ri, -Ri.transpose()*t); } if (!logging_file_.empty()) { Save(sfm_data_, stlplus::create_filespec(stlplus::folder_part(logging_file_), "cameraPath_translation_averaging", "ply"), ESfM_Data(EXTRINSICS)); } return true; } /// Compute the initial structure of the scene bool StellarSfMReconstructionEngine::Compute_Initial_Structure(const int min_covisibility) { // Build tracks { using namespace openMVG::tracks; TracksBuilder tracksBuilder; tracksBuilder.Build(matches_provider_->pairWise_matches_); tracksBuilder.Filter(min_covisibility); STLMAPTracks map_selectedTracks; // reconstructed track (visibility per 3D point) tracksBuilder.ExportToSTL(map_selectedTracks); // Fill sfm_data with the computed tracks (no 3D yet) Landmarks & structure = sfm_data_.structure; IndexT idx(0); for (const auto & tracks_it : map_selectedTracks) { const submapTrack & track = tracks_it.second; structure[idx] = Landmark(); Observations & obs = structure.at(idx).obs; for (const auto & track_it : track) { const size_t ima_index = track_it.first; const size_t feat_index = track_it.second; const PointFeature & pt = features_provider_->feats_per_view.at(ima_index)[feat_index]; obs[ima_index] = std::move(Observation(pt.coords().cast<double>(), feat_index)); } ++idx; } } // Ensure tracks are visible by some poses const IndexT minPointPerPose = 12; // 6 min const IndexT minTrackLength = 2; // 2 min eraseUnstablePosesAndObservations(sfm_data_, minPointPerPose, minTrackLength); // Compute 3D position of the landmark of the structure by triangulation of the observations { openMVG::system::Timer timer; const IndexT trackCountBefore = sfm_data_.GetLandmarks().size(); SfM_Data_Structure_Computation_Blind structure_estimator(true); structure_estimator.triangulate(sfm_data_); // // Remove unstable depth points DepthCleaning(sfm_data_); OPENMVG_LOG_INFO << "#removed tracks (invalid triangulation): " << trackCountBefore - IndexT(sfm_data_.GetLandmarks().size()); OPENMVG_LOG_INFO << " Triangulation took (s): " << timer.elapsed(); // Export initial structure if (!logging_file_.empty()) { Save(sfm_data_, stlplus::create_filespec(stlplus::folder_part(logging_file_), "initial_structure", "ply"), ESfM_Data(EXTRINSICS | STRUCTURE)); } } return !sfm_data_.structure.empty(); } bool StellarSfMReconstructionEngine::Adjust() { if (ReconstructionEngine::intrinsic_refinement_options_ != cameras::Intrinsic_Parameter_Type::NONE) { Bundle_Adjustment_Ceres::BA_Ceres_options options; if ( sfm_data_.GetPoses().size() > 100 ) // Try enable sparse BA only if a sparse lib is available and if there more than 100 poses { // Descending priority order by efficiency (SUITE_SPARSE > EIGEN_SPARSE) if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE)) { options.sparse_linear_algebra_library_type_ = ceres::SUITE_SPARSE; options.preconditioner_type_ = ceres::JACOBI; options.linear_solver_type_ = ceres::SPARSE_SCHUR; } else { if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::EIGEN_SPARSE)) { options.sparse_linear_algebra_library_type_ = ceres::EIGEN_SPARSE; options.preconditioner_type_ = ceres::JACOBI; options.linear_solver_type_ = ceres::SPARSE_SCHUR; } } } else { options.linear_solver_type_ = ceres::DENSE_SCHUR; } Bundle_Adjustment_Ceres bundle_adjustment_obj(options); options.max_linear_solver_iterations_ = 100; options.parameter_tolerance_ = 0.0; options.gradient_tolerance_ = 1.0; const Optimize_Options ba_refine_options ( ReconstructionEngine::intrinsic_refinement_options_, Extrinsic_Parameter_Type::ADJUST_ALL, // Adjust camera motion Structure_Parameter_Type::ADJUST_ALL, // Adjust scene structure Control_Point_Parameter(), this->b_use_motion_prior_ ); bool b_BA_Status = bundle_adjustment_obj.Adjust(sfm_data_, ba_refine_options); if (b_BA_Status) { DepthCleaning(sfm_data_); } if (b_BA_Status && !logging_file_.empty()) { Save(sfm_data_, stlplus::create_filespec(stlplus::folder_part(logging_file_), "structure_ba", "ply"), ESfM_Data(EXTRINSICS | STRUCTURE)); // Remove outliers (max_angle, residual error) // Remove unstable triangulations and camera poses RemoveOutliers_AngleError(sfm_data_, 2.0); RemoveOutliers_PixelResidualError(sfm_data_, 4.0); eraseUnstablePosesAndObservations(sfm_data_); b_BA_Status = bundle_adjustment_obj.Adjust(sfm_data_, ba_refine_options); if (b_BA_Status) { // Remove unstable depth points DepthCleaning(sfm_data_); } Save(sfm_data_, stlplus::create_filespec(stlplus::folder_part(logging_file_), "structure_ba_outlier_removed", "ply"), ESfM_Data(EXTRINSICS | STRUCTURE)); return b_BA_Status; } } return true; } } // namespace sfm } // namespace openMVG
27,887
C++
.cpp
708
34.247175
130
0.681744
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,604
convert_test.cpp
openMVG_openMVG/src/openMVG/spherical/convert_test.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2020 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/spherical/cubic_image_sampler.hpp" #include "openMVG/image/image_io.hpp" #include "testing/testing.h" using namespace openMVG; using namespace openMVG::image; using namespace openMVG::cameras; // Define some global variable that gonna be shared by the various demo sample static const int cubic_size = 256; static const std::vector<Image<RGBColor>> images = { Image<RGBColor>(cubic_size, cubic_size, true, BLUE), Image<RGBColor>(cubic_size, cubic_size, true, RED), Image<RGBColor>(cubic_size, cubic_size, true, GREEN), Image<RGBColor>(cubic_size, cubic_size, true, YELLOW), Image<RGBColor>(cubic_size, cubic_size, true, CYAN), Image<RGBColor>(cubic_size, cubic_size, true, MAGENTA) }; static const openMVG::cameras::Pinhole_Intrinsic pinhole_camera = spherical::ComputeCubicCameraIntrinsics(cubic_size); static const std::array<openMVG::Mat3,6> cubic_image_rotations = spherical::GetCubicRotations(); // Project each pinhole on a sphere static const Intrinsic_Spherical spherical_camera(512, 256); void SphericalToPinholeIndirect ( Image<RGBColor> & spherical_image ) { // Compute the projection of the tiles on the pano (indirect) // For each pixel of the spherical image, find back which tile pixel project on it { for (int x = 0; x < spherical_image.Width(); ++x) for (int y = 0; y < spherical_image.Height(); ++y) { // Build a bearing vector const Vec3 bearing_vector = spherical_camera(Vec2(x + .5,y + .5)); // See if the bearing_vector reproject on a pinhole images for (const int i_rot : {0, 1, 2, 3, 4, 5}) // For every rotation { const Mat3 rotation_matrix = cubic_image_rotations[i_rot]; const Vec2 proj = pinhole_camera.project(rotation_matrix * bearing_vector); const Vec3 pinhole_cam_look_dir = rotation_matrix.transpose() * pinhole_camera(Vec2(spherical_image.Width()/2,spherical_image.Height()/2)); const auto & pinhole_image = images[i_rot]; if (// Look if the projection is projecting into the image plane proj.x() > 0 && proj.x() < pinhole_image.Width() && proj.y() > 0 && proj.y() < pinhole_image.Height() && // Look if the camera and the sampled sphere vector are looking in the same direction pinhole_cam_look_dir.dot(bearing_vector) > 0.0 ) { spherical_image(y, x) = pinhole_image((int)proj.y(), (int)proj.x()); break; } } } } } TEST(Ressampling, PinholeToSpherical_indirect_mapping) { Image<RGBColor> spherical_image(512, 256); SphericalToPinholeIndirect(spherical_image); WriteImage("test_pinhole_to_spherical_indirect.png", spherical_image); } TEST(Ressampling, PinholeToSpherical_direct_mapping) { Image<RGBColor> spherical_image(512, 256); for (const int i_rot : {0, 1, 2, 3, 4, 5}) // For every rotation { const auto & pinhole_image = images[i_rot]; const Mat3 rotation_matrix = cubic_image_rotations[i_rot]; // Project each pixel Mat2X xy_coords(2, static_cast<int>(cubic_size * cubic_size)); for (int x = 0; x < cubic_size; ++x) for (int y = 0; y < cubic_size; ++y) xy_coords.col(x + cubic_size * y ) << x + .5, y +.5; // Compute bearing vectors const Mat3X bearing_vectors = pinhole_camera(xy_coords); // Compute rotated bearings const Mat3X rotated_bearings = rotation_matrix.transpose() * bearing_vectors; for (int it = 0; it < rotated_bearings.cols(); ++it) { // Project the bearing vector to the sphere const Vec2 sphere_proj = spherical_camera.project(rotated_bearings.col(it)); // and use the corresponding pixel location in the panorama const Vec2 xy = xy_coords.col(it); if (spherical_image.Contains(sphere_proj.y(), sphere_proj.x())) { spherical_image(sphere_proj.y(), sphere_proj.x()) = pinhole_image((int)xy.y(),(int)xy.x()); } } } WriteImage("test_pinhole_to_spherical_direct.png", spherical_image); // Notes: // Since the projection is direct, we project only the pixel from the pinhole to the spherical domain // -> It's gonna create hole in the spherical image for top and bottom image // The indirect mapping is sampling from destimation to source // Direct mapping is mapping from source to destination and so cannot fill all the pixel if the cubic image is small } TEST(Ressampling, PinholeToSpherical_SphericalToPinhole) { Image<RGBColor> spherical_image(512, 256); SphericalToPinholeIndirect(spherical_image); openMVG::cameras::Pinhole_Intrinsic pinhole_camera = spherical::ComputeCubicCameraIntrinsics(64); std::vector<Image<RGBColor>> cube_images; spherical::SphericalToCubic(spherical_image, pinhole_camera, cube_images, image::Sampler2d<image::SamplerNearest>()); WriteImage("cube_0.png", cube_images[0]); WriteImage("cube_1.png", cube_images[1]); WriteImage("cube_2.png", cube_images[2]); WriteImage("cube_3.png", cube_images[3]); WriteImage("cube_4.png", cube_images[4]); WriteImage("cube_5.png", cube_images[5]); //WriteImage("test_pinhole_to_spherical_indirect.png", spherical_image); } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */
5,697
C++
.cpp
121
42.859504
147
0.683633
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,621
color_gradient_test.cpp
openMVG_openMVG/src/openMVG/graphics/color_gradient_test.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2019 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/graphics/color_gradient.hpp" #include "openMVG/image/image_container.hpp" #include "openMVG/image/image_io.hpp" #include "testing/testing.h" using namespace openMVG; using namespace openMVG::image; using namespace openMVG::graphics; TEST(ColorGradient, BoundCheck) { const Color_Gradient heatMapGradient(Color_Gradient::k2BlueRedHeatMap()); float r, g, b; heatMapGradient.getColor(0.f, r, g, b); EXPECT_EQ(0.f, r); EXPECT_EQ(0.f, g); EXPECT_EQ(1.f, b); heatMapGradient.getColor(1.f, r, g, b); EXPECT_EQ(1.f, r); EXPECT_EQ(0.f, g); EXPECT_EQ(0.f, b); heatMapGradient.getColor(.5f, r, g, b); EXPECT_EQ(.5f, r); EXPECT_EQ(0.f, g); EXPECT_EQ(.5f, b); } TEST(ColorGradient, GradientDemo) { const int w = 100, h = 10; Image<RGBColor> image(w, h); image.fill(BLACK); { const Color_Gradient heatMapGradient(Color_Gradient::k2BlueRedHeatMap()); float r, g, b; for (int i = 0; i < w; ++i) { heatMapGradient.getColor(static_cast<float>(i) / w, r, g, b); image.col(i).fill(RGBColor(r * 255, g * 255, b * 255)); } EXPECT_TRUE(WriteImage("color_gradient_2Colors.png", image)); } { const Color_Gradient heatMapGradient; float r, g, b; for (int i = 0; i < w; ++i) { heatMapGradient.getColor(static_cast<float>(i) / w, r, g, b); image.col(i).fill(RGBColor(r * 255, g * 255, b * 255)); } EXPECT_TRUE(WriteImage("color_gradient_5Colors.png", image)); } } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */
2,029
C++
.cpp
56
32.875
79
0.623018
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
26,632
progress_test.cpp
openMVG_openMVG/src/openMVG/system/progress_test.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (C) 2017 Bjorn Piltz, Pierre Moulon // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/system/progressinterface.hpp" #include "openMVG/system/loggerprogress.hpp" #include "testing/testing.h" #include <set> #ifdef OPENMVG_USE_OPENMP #include <omp.h> #endif static const int Count = 100*1000; static const int num_threads = 10; using openMVG::system::ProgressInterface; // This function counts to Count int singleThreadedCount(ProgressInterface * progress=nullptr) { if (!progress) progress = &ProgressInterface::dummy(); int result = 0; for (int i = 0; i<Count; i++) { if (progress->hasBeenCanceled()) break; ++result; ++(*progress); } return result; } // This function counts to Count int multiThreadedCount(ProgressInterface * progress=nullptr) { if (!progress) progress = &ProgressInterface::dummy(); int result = 0; #ifdef OPENMVG_USE_OPENMP omp_set_num_threads(num_threads); #pragma omp parallel for #endif for (int i = 0; i<Count; i++) { if (progress->hasBeenCanceled()) // We are not allowed to use 'break' in an omp loop, continue; #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { ++result; ++(*progress); } } return result; } class MockProgress : public ProgressInterface { public: virtual void Restart(const std::uint32_t expected_count, const std::string& msg = {})override { ProgressInterface::Restart(expected_count, msg); this->ulExpected_count = expected_count; this->currentCount = 0; } virtual bool hasBeenCanceled()const override { return false; } virtual std::uint32_t operator+=(const std::uint32_t increment) override { ProgressInterface::operator+=(increment); ++currentCount; return currentCount; } std::uint32_t ulExpected_count = 0, currentCount = 0; }; class CancelProgress : public MockProgress { virtual bool hasBeenCanceled()const override { return true; } }; template<int CancelAtNumber> class CancelAt : public MockProgress { virtual bool hasBeenCanceled()const override { return currentCount==CancelAtNumber; } }; TEST(Progress, dummy) { // Make sure the singleThreadedCount() works with the default dummy progress EXPECT_EQ(Count, singleThreadedCount()); // Make sure the multiThreadedCount() works with the default dummy progress EXPECT_EQ(Count, multiThreadedCount()); MockProgress progress; EXPECT_EQ(Count, singleThreadedCount(&progress)); EXPECT_EQ(Count, progress.currentCount); progress.Restart(Count); EXPECT_EQ(Count, multiThreadedCount(&progress)); EXPECT_EQ(Count, progress.currentCount); } TEST(Progress, cancel) { // Make sure the singleThreadedCount() works with MockProgress CancelProgress progress; EXPECT_EQ(0, singleThreadedCount(&progress)); progress.Restart(Count); EXPECT_EQ(0, multiThreadedCount(&progress)); CancelAt<13> cancelAtThirteen; EXPECT_EQ(13, singleThreadedCount(&cancelAtThirteen)); } TEST(Progress, percent) { ProgressInterface progress(10); EXPECT_EQ(10, progress.expected_count()); EXPECT_EQ(0, progress.count()); EXPECT_EQ(0, progress.Percent()); progress += 2; EXPECT_EQ(2, progress.count()); EXPECT_EQ(20, progress.Percent()); progress += 4; EXPECT_EQ(6, progress.count()); EXPECT_EQ(60, progress.Percent()); progress += 4; EXPECT_EQ(10, progress.count()); EXPECT_EQ(100, progress.Percent()); } using openMVG::system::LoggerProgress; TEST(LogProgress, logging) { LoggerProgress progress(10); for (int i = 0; i < 10; ++i) { ++progress; } } TEST(LogProgress, logging_if) { LoggerProgress progress(10); for (int i = 0; i < 10; ++i) { const bool b_update_progress_required = progress.Increment(1); OPENMVG_LOG_INFO_IF(b_update_progress_required) << progress.PercentString(); } } // Check that every pourcentage is displayed once TEST(LogProgress, conditional_logging) { LoggerProgress progress(800, "", 2); std::set<int> previously_displayed_percentage; for (int i = 0; i < progress.count(); ++i) { if (progress.Increment(1)) // If display is triggered { EXPECT_EQ(0, previously_displayed_percentage.count(progress.Percent())); previously_displayed_percentage.insert(progress.Percent()); } } } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr); } /* ************************************************************************* */
4,766
C++
.cpp
165
26.006061
95
0.70291
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,648
union_find_test.cpp
openMVG_openMVG/src/openMVG/tracks/union_find_test.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2019 Pierre MOULON // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/tracks/union_find.hpp" #include "CppUnitLite/TestHarness.h" #include "testing/testing.h" #include <set> using namespace openMVG; TEST(Tracks, union_find_logic) { // Initialize the union_find tree the track four element: {0, 1, 2, 3} UnionFind uf_tree; uf_tree.InitSets(4); // ids from 0 to 4 EXPECT_EQ(4, uf_tree.GetNumNodes()); // Link 0 and 1 uf_tree.Union(0, 1); EXPECT_EQ(uf_tree.Find(0), uf_tree.Find(1)); // The component id of 1,2,3 should not be linked CHECK(uf_tree.Find(1) != uf_tree.Find(2)); CHECK(uf_tree.Find(2) != uf_tree.Find(3)); // Link 0 to self (should not crash) uf_tree.Union(0, 0); // Link 2 to 3 uf_tree.Union(2, 3); EXPECT_EQ(uf_tree.Find(2), uf_tree.Find(3)); CHECK(uf_tree.Find(1) != uf_tree.Find(2)); // Link 1 and 2 // It creates the link 1->2 and link the two previously existing component (0->1; 2->3) uf_tree.Union(1, 2); EXPECT_EQ(uf_tree.Find(1), uf_tree.Find(2)); EXPECT_EQ(uf_tree.Find(0), uf_tree.Find(3)); } TEST(Tracks, one_cc) { UnionFind uf_tree; uf_tree.InitSets(5); // Create the connections: 0-1-2-3-4 uf_tree.Union(0, 1); uf_tree.Union(1, 2); uf_tree.Union(3, 4); uf_tree.Union(1, 3); // Run path compression to identify all the point belonging to the CC for (unsigned int i = 0; i < uf_tree.GetNumNodes(); ++i) uf_tree.Find(i); // Count the number of CC const std::set<unsigned int> parent_id(uf_tree.m_cc_parent.cbegin(), uf_tree.m_cc_parent.cend()); EXPECT_EQ(1, parent_id.size()); } TEST(Tracks, two_cc) { UnionFind uf_tree; uf_tree.InitSets(4); // Create the following connections // 0-1 // 2-3 uf_tree.Union(0, 1); uf_tree.Union(2, 3); // Run path compression to identify all the point belonging to the CC for (unsigned int i = 0; i < uf_tree.GetNumNodes(); ++i) uf_tree.Find(i); // Count the number of CC const std::set<unsigned int> parent_id(uf_tree.m_cc_parent.cbegin(), uf_tree.m_cc_parent.cend()); EXPECT_EQ(2, parent_id.size()); } TEST(Tracks, four_cc) { UnionFind uf_tree; uf_tree.InitSets(6); // Create the following connections // 0-1 // 2-3 // 4 // 5 uf_tree.Union(0, 1); uf_tree.Union(2, 3); // Run path compression to identify all the point belonging to the CC for (unsigned int i = 0; i < uf_tree.GetNumNodes(); ++i) uf_tree.Find(i); // Count the number of CC const std::set<unsigned int> parent_id(uf_tree.m_cc_parent.cbegin(), uf_tree.m_cc_parent.cend()); EXPECT_EQ(4, parent_id.size()); } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */
3,077
C++
.cpp
83
34.156627
99
0.640135
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
26,651
indMatch_utils.cpp
openMVG_openMVG/src/openMVG/matching/indMatch_utils.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // The <cereal/archives> headers are special and must be included first. #include <cereal/archives/portable_binary.hpp> #include "openMVG/matching/indMatch_utils.hpp" #include "openMVG/matching/indMatch_io.hpp" #include "openMVG/system/logger.hpp" #include <algorithm> #include <fstream> #include <iterator> #include <map> #include <vector> #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cereal/types/map.hpp> #include <cereal/types/utility.hpp> #include <cereal/types/vector.hpp> namespace openMVG { namespace matching { bool Load ( PairWiseMatches & matches, const std::string & filename ) { matches.clear(); std::ifstream stream; const std::string ext = stlplus::extension_part(filename); if (ext == "txt") { stream.open(filename); if (stream) { // Read from the text file // I J // #matches count // idx idx // ... size_t I, J, number; while (stream >> I >> J >> number) { std::vector<IndMatch> read_matches(number); for (size_t i = 0; i < number; ++i) { stream >> read_matches[i]; } matches[{I,J}] = std::move(read_matches); } stream.clear(); // necessary since we hit eof with the while stream.close(); } } else if (ext == "bin") { stream.open(filename.c_str(), std::ios::in | std::ios::binary); if (stream) { cereal::PortableBinaryInputArchive archive(stream); archive(matches); stream.close(); } } else { OPENMVG_LOG_ERROR << "Unknown PairWiseMatches file extension: (" << ext << ")."; } if (!stream) { OPENMVG_LOG_ERROR << "Cannot open the matche file: " << filename << "."; } return static_cast<bool>(stream); } bool Save ( const PairWiseMatches & matches, const std::string & filename ) { const std::string ext = stlplus::extension_part(filename); std::ofstream stream; if (ext == "txt") { stream.open(filename); if (stream) { for ( const auto & cur_match : matches ) { const auto& I = cur_match.first.first; const auto& J = cur_match.first.second; const std::vector<IndMatch> & pair_matches = cur_match.second; stream << I << " " << J << '\n' << pair_matches.size() << '\n'; copy(pair_matches.cbegin(), pair_matches.cend(), std::ostream_iterator<IndMatch>(stream, "\n")); } stream.close(); } } else if (ext == "bin") { stream.open(filename.c_str(), std::ios::out | std::ios::binary); if (stream) { cereal::PortableBinaryOutputArchive archive(stream); archive(matches); stream.close(); } } else { OPENMVG_LOG_ERROR << "Unknown PairWiseMatches output file extension: " << filename; } if (!stream) { OPENMVG_LOG_ERROR << "Cannot save the matche file: " << filename << "."; } return static_cast<bool>(stream); } } // namespace matching } // namespace openMVG
3,303
C++
.cpp
119
23.571429
87
0.63817
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,659
kmeans_test.cpp
openMVG_openMVG/src/openMVG/clustering/kmeans_test.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 Romuald Perrot. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/clustering/kmeans.hpp" #include "testing/testing.h" #include <random> #include <vector> using namespace openMVG; using namespace clustering; // Define test constant: static const int NB_CLUSTER = 3; static const int NB_POINT = 1e4; static const std::array<int, 3> POINTS_PER_CLUSTER = {NB_POINT, NB_POINT, NB_POINT}; static const std::array<KMeansInitType, 2> KMEAN_INIT_TYPES = {KMeansInitType::KMEANS_INIT_RANDOM, KMeansInitType::KMEANS_INIT_PP}; // Initialize NB_CLUSTER centers and POINTS_PER_CLUSTER[i] points around each centroid // Note: Clusters and points are column based // The function return all the points randomly initialized around the centroid. Mat InitRandom3ClusterDataset ( Mat & centers, const int dimension ) { centers.resize(dimension, NB_CLUSTER); centers.col(0).setConstant(-5.0); centers.col(1).setConstant(5.0); centers.col(2).setConstant(0.0); // Initialize a list of points around the centroids Mat points(dimension, std::accumulate(POINTS_PER_CLUSTER.cbegin(), POINTS_PER_CLUSTER.cend(), 0)); std::mt19937_64 rng(std::mt19937_64::default_seed); std::uniform_real_distribution<double> distrib(-2.0, 2.0); // Generate points on each centers int point_id = 0; for (int cluster_id = 0; cluster_id < NB_CLUSTER; ++cluster_id) { for (int id = 0; id < POINTS_PER_CLUSTER[cluster_id]; ++id) { Vec random_point(dimension); for (int i = 0; i < dimension; ++i) random_point(i) = distrib(rng); points.col(point_id) = random_point + centers.col(cluster_id); ++point_id; } } return points; } // Template function to convert the data_point dataset to various type template <typename T> T ConvertMat2T(const Mat & mat); // Predicate to test if two element are the same bool EqualPredicate (uint32_t i, uint32_t j) { return (i==j); } // Template function to make the testing of KMeans easier // It avoids some code duplication template<typename ContainerType> void KMeanTesting ( std::vector< uint32_t > & ids, std::vector< typename ContainerType::value_type > & centers, const int dimension, const KMeansInitType k_mean_init_type, const uint32_t k_mean_centers = 3 ) { // Data initialization (centers and data_points) Mat mat_centers; const Mat mat_points = InitRandom3ClusterDataset(mat_centers, dimension); const ContainerType pts = ConvertMat2T<ContainerType>(mat_points); // K-Means clustering: KMeans(pts, ids, centers, k_mean_centers, std::numeric_limits<uint32_t>::max(), k_mean_init_type ); } // Check the result of the KMean Ids classification #define KMEANS_CHECK_VALIDITY(NB_CLUSTER, ids) \ {\ /* Does the right number of cluster are found?*/\ EXPECT_EQ(NB_CLUSTER, centers.size());\ \ /* Does points are labelled to valid cluster ids?*/\ {\ std::vector< uint32_t > ids_cpy(ids.size());\ const auto it = std::unique_copy (ids.cbegin(),ids.cend(),ids_cpy.begin(), EqualPredicate);\ ids_cpy.resize( std::distance(ids_cpy.begin(), it) );\ EXPECT_EQ(NB_CLUSTER, ids_cpy.size());\ }\ \ /* Does points are labelled to the right centroid id?*/\ int counter = 0;\ for (const auto nb_point_in_cluster : POINTS_PER_CLUSTER)\ {\ const int id_to_check = ids[counter];\ for (int i = 0; i < nb_point_in_cluster; ++i)\ {\ EXPECT_EQ(id_to_check, ids[counter]);\ ++counter;\ }\ }\ } // std::vector<Vec2> specialization template <> std::vector< Vec2 > ConvertMat2T<std::vector< Vec2 >> ( const Mat & mat ) { std::vector< Vec2 > pts(mat.cols()); for (int i = 0; i < mat.cols(); ++i) pts[i] = mat.col(i); return pts; } TEST( clustering, threeClustersVec2 ) { const int dimension = 2; using DataPointType = Vec2; using ContainerType = std::vector<DataPointType>; for (const auto kmean_init_type : KMEAN_INIT_TYPES) { std::vector<uint32_t> ids; std::vector<DataPointType> centers; KMeanTesting<ContainerType> ( ids, centers, dimension, kmean_init_type ); KMEANS_CHECK_VALIDITY(NB_CLUSTER, ids); std::cout << "Centers with kmean init type(" << (int)kmean_init_type << "): " << std::endl; for( const auto & it : centers ) { std::cout << it.transpose() << std::endl; } } } // std::vector<Vec3> specialization template <> std::vector< Vec3 > ConvertMat2T<std::vector< Vec3 >>(const Mat & mat) { std::vector< Vec3 > pts(mat.cols()); for (int i = 0; i < mat.cols(); ++i) pts[i] = mat.col(i); return pts; } TEST( clustering, threeClustersVec3 ) { const int dimension = 3; using DataPointType = Vec3; using ContainerType = std::vector<DataPointType>; for (const auto kmean_init_type : KMEAN_INIT_TYPES) { std::vector<uint32_t> ids; std::vector<DataPointType> centers; KMeanTesting<ContainerType> ( ids, centers, dimension, kmean_init_type ); KMEANS_CHECK_VALIDITY(NB_CLUSTER, ids); std::cout << "Centers with kmean init type(" << (int)kmean_init_type << "): " << std::endl; for( const auto & it : centers ) { std::cout << it.transpose() << std::endl; } } } // std::vector<std::array<double, 5>> specialization template <> std::vector<std::array<double, 5>> ConvertMat2T<std::vector<std::array<double, 5>>>(const Mat & mat) { std::vector<std::array<double, 5>> pts(mat.cols()); for (int i = 0; i < mat.cols(); ++i) std::copy(mat.col(i).data(), mat.col(i).data()+5, pts[i].data()); return pts; } TEST( clustering, threeClustersStdArray ) { const int dimension = 5; using DataPointType = std::array<double, 5>; using ContainerType = std::vector<DataPointType>; for (const auto kmean_init_type : KMEAN_INIT_TYPES) { std::vector<uint32_t> ids; std::vector<DataPointType> centers; KMeanTesting<ContainerType> ( ids, centers, dimension, kmean_init_type ); KMEANS_CHECK_VALIDITY(NB_CLUSTER, ids); std::cout << "Centers with kmean init type(" << (int)kmean_init_type << "): " << std::endl; for( const auto & center : centers ) { for (const auto val : center) std::cout << val << " "; std::cout << std::endl; } } } // std::vector<std::vector<double>> specialization template <> std::vector<std::vector<double>> ConvertMat2T<std::vector<std::vector<double>>>(const Mat & mat) { std::vector<std::vector<double>> pts(mat.cols()); for (int i = 0; i < mat.cols(); ++i) pts[i].assign(mat.col(i).data(), mat.col(i).data() + mat.rows()); return pts; } TEST( clustering, threeClustersStdVector ) { const int dimension = 12; using DataPointType = std::vector<double>; using ContainerType = std::vector<DataPointType>; for (const auto kmean_init_type : KMEAN_INIT_TYPES) { std::vector<uint32_t> ids; std::vector<DataPointType> centers; KMeanTesting<ContainerType> ( ids, centers, dimension, kmean_init_type ); KMEANS_CHECK_VALIDITY(NB_CLUSTER, ids); std::cout << "Centers with kmean init type(" << (int)kmean_init_type << "): " << std::endl; for( const auto & center : centers ) { for (const auto val : center) std::cout << val << " "; std::cout << std::endl; } } } // std::vector<Vec> specialization template <> std::vector< Vec > ConvertMat2T<std::vector< Vec >>(const Mat & mat) { std::vector< Vec > pts(mat.cols()); for (int i = 0; i < mat.cols(); ++i) pts[i] = mat.col(i); return pts; } TEST( clustering, threeClustersEigenVec ) { const int dimension = 6; using DataPointType = Vec; using ContainerType = std::vector<DataPointType>; for (const auto kmean_init_type : KMEAN_INIT_TYPES) { std::vector<uint32_t> ids; std::vector<DataPointType> centers; KMeanTesting<ContainerType> ( ids, centers, dimension, kmean_init_type ); KMEANS_CHECK_VALIDITY(NB_CLUSTER, ids); std::cout << "Centers with kmean init type(" << (int)kmean_init_type << "): " << std::endl; for( const auto & it : centers ) { std::cout << it.transpose() << std::endl; } } } // std::vector<Vecf> specialization template <> std::vector< Vecf > ConvertMat2T<std::vector< Vecf >>(const Mat & mat) { std::vector< Vecf > pts(mat.cols()); for (int i = 0; i < mat.cols(); ++i) pts[i] = mat.col(i).cast<float>(); return pts; } TEST( clustering, threeClustersEigenVecf ) { const int dimension = 6; using DataPointType = Vecf; using ContainerType = std::vector<DataPointType>; for (const auto kmean_init_type : KMEAN_INIT_TYPES) { std::vector<uint32_t> ids; std::vector<DataPointType> centers; KMeanTesting<ContainerType> ( ids, centers, dimension, kmean_init_type ); KMEANS_CHECK_VALIDITY(NB_CLUSTER, ids); std::cout << "Centers with kmean init type(" << (int)kmean_init_type << "): " << std::endl; for( const auto & it : centers ) { std::cout << it.transpose() << std::endl; } } } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests( tr ); } /* ************************************************************************* */
9,670
C++
.cpp
321
26.35514
96
0.64814
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
26,707
solver_resection_p3p_ding.cpp
openMVG_openMVG/src/openMVG/multiview/solver_resection_p3p_ding.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2024 Yaqing Ding // Some of the scripts are based on Mark Shachkov (mark.shachkov@gmail.com) and // the Lambda-twist P3P implementation Adapted to openMVG by Pierre Moulon // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/multiview/solver_resection_p3p_ding.hpp" #include "openMVG/multiview/projection.hpp" #include <array> namespace openMVG { namespace euclidean_resection { /** * @brief Refine a valid solution with a Gauss-Newton Solver. * @param lambda Valid lambdas * @param a12 is the squared distance between X1 and X2 * @param a13 is the squared distance between X1 and X3 * @param a23 is the squared distance between X2 and X3 * @param b12 is the cosine of the angle between bearing vector 1 and bearing * vector 2 * @param b13 is the cosine of the angle between bearing vector 1 and bearing * vector 3 * @param b23 is the cosine of the angle between bearing vector 2 and bearing * vector 3 The paper note it rarely improve after two iterations. The original * implementation use 5 iterations. */ static void gauss_newton_refineL(double &lambda1, double &lambda2, double &lambda3, const double &a12, const double &a13, const double &a23, const double &b12, const double &b13, const double &b23) { for (int iter = 0; iter < 5; ++iter) { double r1 = (lambda1 * lambda1 - 2.0 * lambda1 * lambda2 * b12 + lambda2 * lambda2 - a12); double r2 = (lambda1 * lambda1 - 2.0 * lambda1 * lambda3 * b13 + lambda3 * lambda3 - a13); double r3 = (lambda2 * lambda2 - 2.0 * lambda2 * lambda3 * b23 + lambda3 * lambda3 - a23); if (std::abs(r1) + std::abs(r2) + std::abs(r3) < 1e-10) return; double x11 = lambda1 - lambda2 * b12; double x12 = lambda2 - lambda1 * b12; double x21 = lambda1 - lambda3 * b13; double x23 = lambda3 - lambda1 * b13; double x32 = lambda2 - lambda3 * b23; double x33 = lambda3 - lambda2 * b23; double detJ = 0.5 / (x11 * x23 * x32 + x12 * x21 * x33); // half minus inverse determinant // This uses the closed form of the inverse for the jacobian. // Due to the zero elements this actually becomes quite nice. lambda1 += (-x23 * x32 * r1 - x12 * x33 * r2 + x12 * x23 * r3) * detJ; lambda2 += (-x21 * x33 * r1 + x11 * x33 * r2 - x11 * x23 * r3) * detJ; lambda3 += (x21 * x32 * r1 - x11 * x32 * r2 - x12 * x21 * r3) * detJ; } }; /** * @brief This function finds a single root of the cubic polynomial equation * @param c2 Coefficient of quadratic parameter * @param c1 Coefficient of linear parameter * @param c0 Coefficient of scalar parameter * @param root the single root output * @return true: if the Discriminant is positive * * h(r) = r^3 + c2*r^2 + c1*r + c0 = 0 * */ bool solve_cubic_single_real(double c2, double c1, double c0, double &root) { double a = c1 - c2 * c2 / 3.0; double b = (2.0 * c2 * c2 * c2 - 9.0 * c2 * c1) / 27.0 + c0; double c = b * b / 4.0 + a * a * a / 27.0; if (c != 0) { if (c > 0) { c = std::sqrt(c); b *= -0.5; root = std::cbrt(b + c) + std::cbrt(b - c) - c2 / 3.0; return true; } else { c = 3.0 * b / (2.0 * a) * std::sqrt(-3.0 / a); root = 2.0 * std::sqrt(-a / 3.0) * std::cos(std::acos(c) / 3.0) - c2 / 3.0; } } else { root = -c2 / 3.0 + (a != 0 ? (3.0 * b / a) : 0); } return false; } /** * @brief This function decomposes a degenerate conic into a pair of lines * @param C The degenerate conic, which can be written as C = p*q^T + q*p^T * @return A pair of lines */ inline std::array<Vec3, 2> compute_pq(Mat3 C) { std::array<Vec3, 2> pq; Mat3 C_adj; C_adj(0, 0) = C(1, 2) * C(2, 1) - C(1, 1) * C(2, 2); C_adj(1, 1) = C(0, 2) * C(2, 0) - C(0, 0) * C(2, 2); C_adj(2, 2) = C(0, 1) * C(1, 0) - C(0, 0) * C(1, 1); C_adj(0, 1) = C(0, 1) * C(2, 2) - C(0, 2) * C(2, 1); C_adj(0, 2) = C(0, 2) * C(1, 1) - C(0, 1) * C(1, 2); C_adj(1, 0) = C_adj(0, 1); C_adj(1, 2) = C(0, 0) * C(1, 2) - C(0, 2) * C(1, 0); C_adj(2, 0) = C_adj(0, 2); C_adj(2, 1) = C_adj(1, 2); Vec3 v; if (C_adj(0, 0) > C_adj(1, 1)) { if (C_adj(0, 0) > C_adj(2, 2)) { v = C_adj.col(0) / std::sqrt(C_adj(0, 0)); } else { v = C_adj.col(2) / std::sqrt(C_adj(2, 2)); } } else if (C_adj(1, 1) > C_adj(2, 2)) { v = C_adj.col(1) / std::sqrt(C_adj(1, 1)); } else { v = C_adj.col(2) / std::sqrt(C_adj(2, 2)); } C(0, 1) -= v(2); C(0, 2) += v(1); C(1, 2) -= v(0); C(1, 0) += v(2); C(2, 0) -= v(1); C(2, 1) += v(0); pq[0] = C.col(0); pq[1] = C.row(0); return pq; } /** * @brief Compute the absolute pose of a camera using three 3D-to-2D * correspondences. Implementation of the paper "Revisiting the P3P Problem". Y * Ding, J Yang, V Larsson, C Olsson, K Åström. CVPR 2023 * * @authors Y Ding, J Yang, V Larsson, C Olsson, K Åström. * * @param[in] bearing_vectors 3x3 matrix with UNITARY feature vectors (each * column is a vector) * @param[in] X 3x3 matrix with corresponding 3D world points (each column is a * point) * @param[out] rotation_translation_solutions vector that will contain the * solutions (up to 4 solutions) * * @return true if at least one solution is found, false if no solution was * found * */ bool computePosesDing( const Mat &bearing_vectors, const Mat &X, std::vector<std::tuple<Mat3, Vec3>> &rotation_translation_solutions) { // Extraction of 3D points vectors Vec3 X0 = X.col(0); Vec3 X1 = X.col(1); Vec3 X2 = X.col(2); Vec3 X01 = X0 - X1; Vec3 X02 = X0 - X2; Vec3 X12 = X1 - X2; double a01 = X01.squaredNorm(); double a02 = X02.squaredNorm(); double a12 = X12.squaredNorm(); // Extraction of feature vectors Vec3 x0 = bearing_vectors.col(0); Vec3 x1 = bearing_vectors.col(1); Vec3 x2 = bearing_vectors.col(2); // Switch the columns of X and x so that BC = |X1 - X2| is the largest // one among {X01, X02, X12} if (a01 > a02) { if (a01 > a12) { std::swap(X0, X2); std::swap(x0, x2); std::swap(a01, a12); X01 = -X12; X02 = -X02; } } else if (a02 > a12) { std::swap(X0, X1); std::swap(x0, x1); std::swap(a02, a12); X01 = -X01; X02 = X12; } const double a12d = 1.0 / a12; const double a = a01 * a12d; const double b = a02 * a12d; const double m01 = x0.dot(x1); const double m02 = x0.dot(x2); const double m12 = x1.dot(x2); // Ugly parameters to simplify the calculation const double m12sq = -m12 * m12 + 1.0; const double m02sq = -1.0 + m02 * m02; const double m01sq = -1.0 + m01 * m01; const double ab = a * b; const double bsq = b * b; const double asq = a * a; const double m013 = -2.0 + 2.0 * m01 * m02 * m12; const double bsqm12sq = bsq * m12sq; const double asqm12sq = asq * m12sq; const double abm12sq = 2.0 * ab * m12sq; // coefficients of the cubic equation const double k3_inv = 1.0 / (bsqm12sq + b * m02sq); const double k2 = k3_inv * ((-1.0 + a) * m02sq + abm12sq + bsqm12sq + b * m013); const double k1 = k3_inv * (asqm12sq + abm12sq + a * m013 + (-1.0 + b) * m01sq); const double k0 = k3_inv * (asqm12sq + a * m01sq); double s; bool G = solve_cubic_single_real(k2, k1, k0, s); // The degenerate conic C = C1+s*C2 Mat3 C; C(0, 0) = -a + s * (1 - b); C(0, 1) = -m02 * s; C(0, 2) = a * m12 + b * m12 * s; C(1, 0) = C(0, 1); C(1, 1) = s + 1; C(1, 2) = -m01; C(2, 0) = C(0, 2); C(2, 1) = C(1, 2); C(2, 2) = -a - b * s + 1; std::array<Vec3, 2> pq = compute_pq(C); Mat3 XX; XX << X01, X02, X01.cross(X02); XX = XX.inverse().eval(); Vec3 v1, v2; Mat3 YY; int n_sols = 0; double d0, d1, d2; for (int i = 0; i < 2; ++i) { // [p0 p1 p2] * [1; x; y] = 0, or [p0 p1 p2] * [d2; d0; d1] = 0 double p0 = pq[i](0); double p1 = pq[i](1); double p2 = pq[i](2); bool switch_12 = std::abs(p0) <= std::abs(p1); if (switch_12) { // eliminate d0 double w0 = -p0 / p1; double w1 = -p2 / p1; double ca = 1.0 / (w1 * w1 - b); double cb = 2.0 * (b * m12 - m02 * w1 + w0 * w1) * ca; double cc = (w0 * w0 - 2 * m02 * w0 - b + 1.0) * ca; double taus[2]; if (!P3PSolver_Nordberg::root2real(cb, cc, taus[0], taus[1])) continue; for (double tau : taus) { if (tau <= 0) continue; // positive only d2 = std::sqrt(a12 / (tau * (tau - 2.0 * m12) + 1.0)); d1 = tau * d2; d0 = (w0 * d2 + w1 * d1); if (d0 < 0) continue; // refine the depths gauss_newton_refineL(d0, d1, d2, a01, a02, a12, m01, m02, m12); v1 = d0 * x0 - d1 * x1; v2 = d0 * x0 - d2 * x2; YY << v1, v2, v1.cross(v2); Mat3 R = YY * XX; rotation_translation_solutions.emplace_back(R, d0 * x0 - R * X0); ++n_sols; } } else { double w0 = -p1 / p0; double w1 = -p2 / p0; double ca = 1.0 / (-a * w1 * w1 + 2 * a * m12 * w1 - a + 1); double cb = 2 * (a * m12 * w0 - m01 - a * w0 * w1) * ca; double cc = (1 - a * w0 * w0) * ca; double taus[2]; if (!P3PSolver_Nordberg::root2real(cb, cc, taus[0], taus[1])) continue; for (double tau : taus) { if (tau <= 0) continue; d0 = std::sqrt(a01 / (tau * (tau - 2.0 * m01) + 1.0)); d1 = tau * d0; d2 = w0 * d0 + w1 * d1; if (d2 < 0) continue; gauss_newton_refineL(d0, d1, d2, a01, a02, a12, m01, m02, m12); v1 = d0 * x0 - d1 * x1; v2 = d0 * x0 - d2 * x2; YY << v1, v2, v1.cross(v2); Mat3 R = YY * XX; rotation_translation_solutions.emplace_back(R, d0 * x0 - R * X0); ++n_sols; } } // if n_sols > 0, we have found at least one solution. If G > 0, It means // that only one line from the pair of lines has intersections with the // conic. Hence, we can skip the second line. if (n_sols > 0 && G) break; } return n_sols > 0; } void P3PSolver_Ding::Solve(const Mat &bearing_vectors, const Mat &X, // 3D points std::vector<Mat34> *models) { assert(3 == bearing_vectors.rows()); assert(3 == X.rows()); assert(bearing_vectors.cols() == X.cols()); std::vector<std::tuple<Mat3, Vec3>> rotation_translation_solutions; if (computePosesDing(bearing_vectors, X, rotation_translation_solutions)) { for (const auto &rot_trans_it : rotation_translation_solutions) { Mat34 P; P_From_KRt(Mat3::Identity(), // intrinsics std::get<0>(rot_trans_it), // rotation std::get<1>(rot_trans_it), // translation &P); models->push_back(P); } } }; } // namespace euclidean_resection } // namespace openMVG
11,243
C++
.cpp
310
31.048387
80
0.564084
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,709
solver_resection_up2p_kukelova.cpp
openMVG_openMVG/src/openMVG/multiview/solver_resection_up2p_kukelova.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2020, Viktor Larsson // Copyright (c) 2020, Pierre MOULON // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/multiview/solver_resection_up2p_kukelova.hpp" #include "openMVG/numeric/numeric.h" using namespace openMVG; namespace openMVG { namespace euclidean_resection { // Port from PoseLib // https://github.com/vlarsson/PoseLib/blob/044c55022ff078f46b65195eda3f467aa85dad49/PoseLib/univariate.cc#L47 /* Solves the quadratic equation a*x^2 + b*x + c = 0 */ int solve_quadratic_real(double a, double b, double c, double roots[2]) { const double b2m4ac = b * b - 4 * a * c; if (b2m4ac < 0) return 0; const double sq = std::sqrt(b2m4ac); // Choose sign to avoid cancellations roots[0] = (b > 0) ? (2 * c) / (-b - sq) : (2 * c) / (-b + sq); roots[1] = c / (a * roots[0]); return 2; } // Port of up2p from PoseLib to OpenMVG // PoseLib, a library that provides a collection of minimal solvers for // camera pose estimation. // See original up2p here https://github.com/vlarsson/PoseLib/blob/master/PoseLib/up2p.cc void UP2PSolver_Kukelova::Solve ( const Mat & x, const Mat & X, std::vector<Mat34> * models ) { Eigen::Matrix<double, 4, 4> A; Eigen::Matrix<double, 4, 2> b; A << -x.col(0)(2), 0, x.col(0)(0), X.col(0)(0) * x.col(0)(2) - X.col(0)(2) * x.col(0)(0), 0, -x.col(0)(2), x.col(0)(1), -X.col(0)(1) * x.col(0)(2) - X.col(0)(2) * x.col(0)(1), -x.col(1)(2), 0, x.col(1)(0), X.col(1)(0) * x.col(1)(2) - X.col(1)(2) * x.col(1)(0), 0, -x.col(1)(2), x.col(1)(1), -X.col(1)(1) * x.col(1)(2) - X.col(1)(2) * x.col(1)(1); b << -2 * X.col(0)(0) * x.col(0)(0) - 2 * X.col(0)(2) * x.col(0)(2), X.col(0)(2) * x.col(0)(0) - X.col(0)(0) * x.col(0)(2), -2 * X.col(0)(0) * x.col(0)(1), X.col(0)(2) * x.col(0)(1) - X.col(0)(1) * x.col(0)(2), -2 * X.col(1)(0) * x.col(1)(0) - 2 * X.col(1)(2) * x.col(1)(2), X.col(1)(2) * x.col(1)(0) - X.col(1)(0) * x.col(1)(2), -2 * X.col(1)(0) * x.col(1)(1), X.col(1)(2) * x.col(1)(1) - X.col(1)(1) * x.col(1)(2); b = A.inverse() * b; const double c2 = b(3, 0); const double c3 = b(3, 1); double qq[2]; const int sols = solve_quadratic_real(1.0, c2, c3, qq); models->clear(); for (int i = 0; i < sols; ++i) { const double q = qq[i]; const double q2 = q * q; const double inv_norm = 1.0 / (1 + q2); const double cq = (1 - q2) * inv_norm; const double sq = 2 * q * inv_norm; Mat3 rotation = Mat3::Identity(); rotation(0, 0) = cq; rotation(0, 2) = sq; rotation(2, 0) = -sq; rotation(2, 2) = cq; Vec3 translation; translation = b.block<3, 1>(0, 0) * q + b.block<3, 1>(0, 1); translation *= -inv_norm; const Mat34 pose = HStack(rotation, translation); models->push_back(pose); } } } // namespace euclidean_resection } // namespace openMVG
3,043
C++
.cpp
65
43.846154
418
0.604124
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,714
solver_resection_p3p_nordberg.cpp
openMVG_openMVG/src/openMVG/multiview/solver_resection_p3p_nordberg.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2018 Michael Persson // Adapted to openMVG by Romain Janvier and Pierre Moulon // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/multiview/solver_resection_p3p_nordberg.hpp" #include "openMVG/multiview/projection.hpp" #include <array> namespace openMVG { namespace euclidean_resection { /** * @brief Refine a valid solution with a Gauss-Newton Solver. * @param L Valid lambdas * @param a12 is the squared distance between X1 and X2 * @param a13 is the squared distance between X1 and X3 * @param a23 is the squared distance between X2 and X3 * @param b12 is the cosine of the angle between bearing vector 1 and bearing vector 2 * @param b13 is the cosine of the angle between bearing vector 1 and bearing vector 3 * @param b23 is the cosine of the angle between bearing vector 2 and bearing vector 3 * The paper note it rarely improve after two iterations. The original implementation use 5 iterations. */ static void gauss_newton_refineL(Vec3 &L, const double & a12, const double & a13, const double & a23, const double & b12, const double & b13, const double & b23) { // const expr makes it easier for the compiler to unroll // TODO(RJ:) I have hardcoded the number of iterations here, it's a template parameter in the original implementation for (int i = 0; i < 5; ++i) { const double l1 = L(0); const double l2 = L(1); const double l3 = L(2); const double r1 = l1 * l1 + l2 * l2 + b12 * l1 * l2 - a12; const double r2 = l1 * l1 + l3 * l3 + b13 * l1 * l3 - a13; const double r3 = l2 * l2 + l3 * l3 + b23 * l2 * l3 - a23; if (std::abs(r1) + std::abs(r2) + std::abs(r3) < 1e-10) break; const double dr1dl1 = 2.0 * l1 + b12 * l2; const double dr1dl2 = 2.0 * l2 + b12 * l1; const double dr2dl1 = 2.0 * l1 + b13 * l3; const double dr2dl3 = 2.0 * l3 + b13 * l1; const double dr3dl2 = 2.0 * l2 + b23 * l3; const double dr3dl3 = 2.0 * l3 + b23 * l2; const Vec3 r(r1, r2, r3); // or skip the inverse and make it explicit... { const double v0 = dr1dl1; const double v1 = dr1dl2; const double v3 = dr2dl1; const double v5 = dr2dl3; const double v7 = dr3dl2; const double v8 = dr3dl3; const double det = 1.0 / (-v0 * v5 * v7 - v1 * v3 * v8); Mat3 Ji; Ji << -v5 * v7, -v1 * v8, v1 * v5, -v3 * v8, v0 * v8, -v0 * v5, v3 * v7, -v0 * v7, -v1 * v3; const Vec3 L1 = Vec3(L) - det * (Ji * r); //%l=l - g*H\G;%inv(H)*G //L=L - g*J\r; //% works because the size is ok! { const double l1 = L1(0); const double l2 = L1(1); const double l3 = L1(2); const double r11 = l1 * l1 + l2 * l2 + b12 * l1 * l2 - a12; const double r12 = l1 * l1 + l3 * l3 + b13 * l1 * l3 - a13; const double r13 = l2 * l2 + l3 * l3 + b23 * l2 * l3 - a23; if (std::abs(r11) + std::abs(r12) + std::abs(r13) > std::abs(r1) + std::abs(r2) + std::abs(r3)) { break; } else L = L1; } } } }; /** * @brief This function finds a single root of the cubic polynomial equation * @param b Coefficient of quadratic parameter * @param c Coefficient of linear parameter * @param d Coefficient of scalar parameter * @return the single root * * h(r) = r^3 + b*r^2 + c*r + d = 0 * * The return root is as stable as possible in the sense that it has as high * derivative as possible. The solution is found by simple Newton-Raphson * iterations, and the trick is to choose the initial solution r0 in a clever * way. * * The initial solution is found by considering 5 cases: * * Cases I and II: h has no stationary points. In this case its derivative * is positive. The inital solution to the NR-iteration is r0 here h has * minimal derivative. * * Case III, IV, and V: has two stationary points, t1 < t2. In this case, * h has negative derivative between t1 and t2. In these cases, we can make * a second order approximation of h around each of t1 and t2, and choose r0 * as the leftmost or rightmost root of these approximations, depending on * whether two, one, or both of h(t1) and h(t2) are > 0. */ static double cubick(const double &b, const double &c, const double &d) { // Choose an initial solution double r0; // not monotonic if (b * b >= 3.0 * c) { // h has two stationary points, compute them // double t1 = t - std::sqrt(diff); const double v = std::sqrt(b * b - 3.0 * c); const double t1 = (-b - v) / (3.0); // Check if h(t1) > 0, in this case make a 2-order approx of h around t1 double k = ((t1 + b) * t1 + c) * t1 + d; if (k > 0.0) { // Find leftmost root of 0.5*(r0 -t1)^2*(6*t1+2*b) + k = 0 r0 = t1 - std::sqrt(-k / (3.0 * t1 + b)); // or use the linear comp too // r0 = t1 - } else { const double t2 = (-b + v) / 3.0; k = ((t2 + b) * t2 + c) * t2 + d; // Find rightmost root of 0.5 * (r0 - t2)^2 * (6 * t2 +2 * b) + k1 = 0 r0 = t2 + std::sqrt(-k / (3.0 * t2 + b)); } } else { // r0=1.0/(cubick_inv(c/d,b/d,1.0/d)); // about half work... // if(std::abs((((r0+b)*r0+c)*r0+d))>1e-10) r0 = -b / 3.0; if (std::abs(((3.0 * r0 + 2.0 * b) * r0 + c)) < 1e-4) r0 += 1; //else r0-=1; //double fx=(((r0+b)*r0+c)*r0+d); r0-=10; if(fx<0) r0+=20; } // Do ITER Newton-Raphson iterations // Break if position of root changes less than 1e-13 // double starterr=std::abs(r0*(r0*(r0 + b) + c) + d); // TODO(RJ:) I have hardcoded the number of iteration here, it's hardcoded in a macro definition in the orginal implementation // according to the author, increasing it could lead to a better solution (more robust) for (unsigned int cnt = 0; cnt < 50; ++cnt) { const double fx = (((r0 + b) * r0 + c) * r0 + d); if ((cnt < 7 || std::abs(fx) > 1e-13)) { const double fpx = ((3.0 * r0 + 2.0 * b) * r0 + c); r0 -= fx / fpx; } else break; } return r0; }; /** * @brief eigwithknown0 eigen decomposition of a matrix which has a 0 eigen value * @param x the input matrix * @param E eigenvectors * @param L eigenvalues */ static void eigwithknown0(const Mat3 &x, Mat3 &E, Vec3 &L) { // one eigenvalue is known to be 0. // the known one... L(2) = 0.0; Vec3 v3(x(3) * x(7) - x(6) * x(4), x(6) * x(1) - x(7) * x(0), x(4) * x(0) - x(3) * x(1)); v3.normalize(); double x01_squared = x(0, 1) * x(0, 1); // get the two other... double b = -x(0, 0) - x(1, 1) - x(2, 2); double c = -x01_squared - x(0, 2) * x(0, 2) - x(1, 2) * x(1, 2) + x(0, 0) * (x(1, 1) + x(2, 2)) + x(1, 1) * x(2, 2); double e1, e2; // roots(poly(x)) P3PSolver_Nordberg::root2real(b, c, e1, e2); if (std::abs(e1) < std::abs(e2)) std::swap(e1, e2); L(0) = e1; L(1) = e2; double mx0011 = -x(0, 0) * x(1, 1); double prec_0 = x(0, 1) * x(1, 2) - x(0, 2) * x(1, 1); double prec_1 = x(0, 1) * x(0, 2) - x(0, 0) * x(1, 2); double e = e1; double tmp = 1.0 / (e * (x(0, 0) + x(1, 1)) + mx0011 - e * e + x01_squared); double a1 = -(e * x(0, 2) + prec_0) * tmp; double a2 = -(e * x(1, 2) + prec_1) * tmp; double rnorm = 1.0 / std::sqrt(a1 * a1 + a2 * a2 + 1.0); a1 *= rnorm; a2 *= rnorm; Vec3 v1(a1, a2, rnorm); // e = e2; double tmp2 = 1.0 / (e2 * (x(0, 0) + x(1, 1)) + mx0011 - e2 * e2 + x01_squared); double a21 = -(e2 * x(0, 2) + prec_0) * tmp2; double a22 = -(e2 * x(1, 2) + prec_1) * tmp2; double rnorm2 = 1.0 / std::sqrt(a21 * a21 + a22 * a22 + 1.0); a21 *= rnorm2; a22 *= rnorm2; Vec3 v2(a21, a22, rnorm2); // optionally remove axb from v1,v2 // costly and makes a very small difference! // v1=(v1-v1.dot(v3)*v3);v1.normalize(); // v2=(v2-v2.dot(v3)*v3);v2.normalize(); // v2=(v2-v1.dot(v2)*v2);v2.normalize(); E << v1(0), v2(0), v3(0), v1(1), v2(1), v3(1), v1(2), v2(2), v3(2); }; /** * @brief Compute the absolute pose of a camera using three 3D-to-2D correspondences. * Implementation of the paper "Lambda Twist: An Accurate Fast Robust Perspective Three Point (P3P) Solver". Persson, M. and Nordberg, K. ECCV 2018 * * @authors Mikael Persson and Klas Nordberg * * @param[in] bearing_vectors 3x3 matrix with UNITARY feature vectors (each column is a vector) * @param[in] X 3x3 matrix with corresponding 3D world points (each column is a point) * @param[out] rotation_translation_solutions vector that will contain the solutions (up to 4 solutions) * * @return true if at least one solution is found, false if no solution was found * */ bool computePosesNordberg( const Mat &bearing_vectors, const Mat &X, std::vector<std::tuple<Mat3, Vec3>> &rotation_translation_solutions) { // Extraction of 3D points vectors const Vec3 & P1 = X.col(0); const Vec3 & P2 = X.col(1); const Vec3 & P3 = X.col(2); // Extraction of feature vectors const Vec3 & f1 = bearing_vectors.col(0); const Vec3 & f2 = bearing_vectors.col(1); const Vec3 & f3 = bearing_vectors.col(2); const double b12 = -2.0 * (f1.dot(f2)); const double b13 = -2.0 * (f1.dot(f3)); const double b23 = -2.0 * (f2.dot(f3)); // implicit creation of Vec3, can be removed const Vec3 d12 = P1 - P2; const Vec3 d13 = P1 - P3; const Vec3 d23 = P2 - P3; const Vec3 d12xd13(d12.cross(d13)); const double a12 = d12.squaredNorm(); const double a13 = d13.squaredNorm(); const double a23 = d23.squaredNorm(); //a*g^3 + b*g^2 + c*g + d = 0 const double c31 = -0.5 * b13; const double c23 = -0.5 * b23; const double c12 = -0.5 * b12; const double blob = (c12 * c23 * c31 - 1.0); const double s31_squared = 1.0 - c31 * c31; const double s23_squared = 1.0 - c23 * c23; const double s12_squared = 1.0 - c12 * c12; double p3 = a13 * (a23 * s31_squared - a13 * s23_squared); double p2 = 2.0 * blob * a23 * a13 + a13 * (2.0 * a12 + a13) * s23_squared + a23 * (a23 - a12) * s31_squared; double p1 = a23 * (a13 - a23) * s12_squared - a12 * a12 * s23_squared - 2.0 * a12 * (blob * a23 + a13 * s23_squared); double p0 = a12 * (a12 * s23_squared - a23 * s12_squared); // double g = 0.0; //p3 is det(D2) so its definietly >0 or its a degenerate case p3 = 1.0 / p3; p2 *= p3; p1 *= p3; p0 *= p3; // get sharpest real root of above... const double g = cubick(p2, p1, p0); // we can swap D1,D2 and the coeffs! // oki, Ds are: //D1=M12*XtX(2,2) - M23*XtX(1,1); //D2=M23*XtX(3,3) - M13*XtX(2,2); //[ a23 - a23*g, (a23*b12)/2, -(a23*b13*g)/2] //[ (a23*b12)/2, a23 - a12 + a13*g, (a13*b23*g)/2 - (a12*b23)/2] //[ -(a23*b13*g)/2, (a13*b23*g)/2 - (a12*b23)/2, g*(a13 - a23) - a12] // gain 13 ns... const double A00 = a23 * (1.0 - g); const double A01 = (a23 * b12) * 0.5; const double A02 = (a23 * b13 * g) * (-0.5); const double A11 = a23 - a12 + a13 * g; const double A12 = b23 * (a13 * g - a12) * 0.5; const double A22 = g * (a13 - a23) - a12; Mat3 A; A << A00, A01, A02, A01, A11, A12, A02, A12, A22; // get sorted eigenvalues and eigenvectors given that one should be zero... Mat3 V; Vec3 L; eigwithknown0(A, V, L); double v = std::sqrt(std::max(0.0, -L(1) / L(0))); int valid = 0; std::array<Vec3, 4> Ls; // use the t=Vl with t2,st2,t3 and solve for t3 in t2 std::array<double, 2> ss = {v,-v}; for(const double s : ss) { // u = V(:, 1) - sV(:,2) const Vec3 U = V.col(0) - s * V.col(1); const double u1 = U(0); const double u2 = U(1); const double u3 = U(2); // we are computing lambda using a linear relation // u1*l1 + u2*l2 + u3*l3=0 // li>0, implies all three ui=0 is degenerate... // if two are zero the third must be // hence at most one can be zero. // divide by the largest for best numerics, // simple version, use the bigger of u1, u2, one will always be non-zero if(std::abs(u1)<std::abs(u2)) {// solve for l2 const double a = (a23 - a12) * u3*u3 - a12 * u2*u2 + a12 * b23 *u2 * u3; const double b = (2.* a23 * u1 * u3 - 2. * a12 * u1*u3 + a12 * b23 * u1 * u2 - a23 * b12 * u2 *u3)/a; const double c = (a23 * u1*u1 - a12 * u1*u1 + a23 * u2*u2 - a23 * b12 *u1 *u2)/a; std::array<double, 2> taus; if (!P3PSolver_Nordberg::root2real(b, c, taus[0], taus[1])) continue; for (const double tau : taus) { if (tau<=0) continue; //(tau^2 + b13*tau + 1)*l1^2 = a13 //positive only const double l1 = std::sqrt(a13 / (tau *(tau + b13) + 1.)); const double l3 = tau * l1; const double l2 = -(u1 * l1 + u3 * l3)/u2; if (l2 <= 0.) continue; Ls[valid] = {l1,l2,l3}; // Vec3 list init ++valid; } } else { // solve for l1 const double w2 = 1./( -u1); const double w0 = u2*w2; const double w1 = u3*w2; const double a = 1.0 / ( (a13 - a12) *w1*w1 - a12 * b13 *w1 - a12); const double b = (a13 * b12 * w1 - a12 * b13 * w0 - 2. * w0 * w1 * (a12 - a13)) * a; const double c = ((a13 - a12) * w0 * w0 + a13 * b12 * w0 + a13) * a; std::array<double, 2> taus; if (!P3PSolver_Nordberg::root2real(b, c, taus[0], taus[1])) continue; for (const double tau : taus) { if(tau<=0.) continue; const double d = a23 / (tau * (b23 + tau) + 1.0); const double l2 = std::sqrt(d); const double l3 = tau * l2; const double l1 = w0 * l2 + w1 * l3; if (l1 <= 0.) continue; Ls[valid] = {l1,l2,l3}; // Vec3 list init ++valid; } } } // if constexpr (refinement_iterations>0) for (int i = 0; i < valid; ++i) { gauss_newton_refineL(Ls[i], a12, a13, a23, b12, b13, b23); } Vec3 ry1, ry2, ry3; Vec3 yd1; Vec3 yd2; Vec3 yd1xd2; Mat3 Xmat; Xmat << d12(0), d13(0), d12xd13(0), d12(1), d13(1), d12xd13(1), d12(2), d13(2), d12xd13(2); Xmat = Xmat.inverse().eval(); for (int i = 0; i < valid; ++i) { // compute the rotation: ry1 = f1 * Ls[i](0); ry2 = f2 * Ls[i](1); ry3 = f3 * Ls[i](2); yd1 = ry1 - ry2; yd2 = ry1 - ry3; yd1xd2 = yd1.cross(yd2); Mat3 Ymat; Ymat << yd1(0), yd2(0), yd1xd2(0), yd1(1), yd2(1), yd1xd2(1), yd1(2), yd2(2), yd1xd2(2); const Mat3 Rs = Ymat * Xmat; rotation_translation_solutions.emplace_back(Rs, ry1 - Rs * P1); } return valid > 0; } void P3PSolver_Nordberg::Solve( const Mat &bearing_vectors, const Mat &X, // 3D points std::vector<Mat34> *models) { assert(3 == bearing_vectors.rows()); assert(3 == X.rows()); assert(bearing_vectors.cols() == X.cols()); std::vector<std::tuple<Mat3, Vec3>> rotation_translation_solutions; if (computePosesNordberg(bearing_vectors, X, rotation_translation_solutions)) { for (const auto & rot_trans_it : rotation_translation_solutions) { Mat34 P; P_From_KRt(Mat3::Identity(), // intrinsics std::get<0>(rot_trans_it), // rotation std::get<1>(rot_trans_it), // translation &P); models->push_back(P); } } }; } // namespace euclidean_resection } // namespace openMVG
15,849
C++
.cpp
415
33
147
0.572284
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
26,723
triangulation.cpp
openMVG_openMVG/src/openMVG/multiview/triangulation.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2016 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/multiview/projection.hpp" #include "openMVG/multiview/triangulation.hpp" #include "openMVG/numeric/numeric.h" namespace openMVG { // HZ 12.2 p.312 void TriangulateDLT ( const Mat34 &P1, const Vec3 &x1, const Mat34 &P2, const Vec3 &x2, Vec4 *X_homogeneous ) { // Solve: // [cross(x0,P0) X = 0] // [cross(x1,P1) X = 0] Mat4 design; design.row(0) = x1[0] * P1.row(2) - x1[2] * P1.row(0); design.row(1) = x1[1] * P1.row(2) - x1[2] * P1.row(1); design.row(2) = x2[0] * P2.row(2) - x2[2] * P2.row(0); design.row(3) = x2[1] * P2.row(2) - x2[2] * P2.row(1); const Eigen::JacobiSVD<Mat4> svd( design, Eigen::ComputeFullV ); ( *X_homogeneous ) = svd.matrixV().col( 3 ); } void TriangulateDLT ( const Mat34 &P1, const Vec3 &x1, const Mat34 &P2, const Vec3 &x2, Vec3 *X_euclidean ) { Vec4 X_homogeneous; TriangulateDLT(P1, x1, P2, x2, &X_homogeneous); (*X_euclidean) = X_homogeneous.hnormalized(); } bool TriangulateDLT ( const Mat3 &R0, const Vec3 &t0, const Vec3 &x0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x1, Vec3 *X ) { Mat34 P0, P1; P0.block<3,3>(0,0) = R0; P1.block<3,3>(0,0) = R1; P0.block<3,1>(0,3) = t0; P1.block<3,1>(0,3) = t1; TriangulateDLT(P0, x0, P1, x1, X); return (R0*(*X) + t0)(2) > 0.0 && (R1*(*X) + t1)(2) > 0.0; } // Helper function // Compute Relative motion between two absolute poses parameterized by Rt // Rotate one bearing vector according to the relative motion inline void AbsoluteToRelative( const Mat3 &R0, const Vec3 &t0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x0, Mat3 &R, Vec3 &t, Vec3 &Rx0 ) { R = R1 * R0.transpose(); t = t1 - R * t0; Rx0 = R * x0; } // Helper function // Compute the 3D point from the outcome of an angular triangulation solver // Return true if the point pass the cheirality test, false otherwise // Lee & Civera Eq. (11) and Table 1 - 4) inline bool Compute3DPoint( const Vec3 &mprime0, const Vec3 &mprime1, const Vec3 &t, const Mat3 &R1, const Vec3 &t1, Vec3 *X) { const Vec3 z = mprime1.cross(mprime0); const double z_squared = z.squaredNorm(); const double lambda0 = z.dot(t.cross(mprime1)) / z_squared; const double lambda1 = z.dot(t.cross(mprime0)) / z_squared; const Vec3 xprime1 = t + lambda0 * mprime0; // x'1 is into the frame of camera1 convert it into the world frame in order to obtain the 3D point *X = R1.transpose() * (xprime1 - t1); // make and return the result of the cheirality test return lambda0 > 0.0 && lambda1 > 0.0; } bool TriangulateL1Angular ( const Mat3 &R0, const Vec3 &t0, const Vec3 &x0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x1, Vec3 *X_euclidean ) { // Table 1 - 1) we compute m0 (Rx0) and m1 (x1) Mat3 R; Vec3 t, Rx0; AbsoluteToRelative(R0, t0, R1, t1, x0, R, t, Rx0); // Table 1 - 2) obtain m'0 and m'1 if(Rx0.normalized().cross(t).squaredNorm() <= x1.normalized().cross(t).squaredNorm()) { const Vec3 n1 = x1.cross(t).normalized(); // Eq. (12) const Vec3 mprime0 = Rx0 - Rx0.dot(n1) * n1; return Compute3DPoint(mprime0, x1, t, R1, t1, X_euclidean); } else { const Vec3 n0 = Rx0.cross(t).normalized(); // Eq. (13) const Vec3 mprime1 = x1 - x1.dot(n0) * n0; return Compute3DPoint(Rx0, mprime1, t, R1, t1, X_euclidean); } } bool TriangulateLInfinityAngular ( const Mat3 &R0, const Vec3 &t0, const Vec3 &x0, const Mat3 &R1, const Vec3 &t1, const Vec3 &x1, Vec3 *X_euclidean ) { // Table 1 - 1) we compute m0 (Rx0) and m1 (x1) Mat3 R; Vec3 t, Rx0; AbsoluteToRelative(R0, t0, R1, t1, x0, R, t, Rx0); // cf. 7. Lemma 2 const Vec3 Rx0_norm = Rx0.normalized(); const Vec3 x1_norm = x1.normalized(); const Vec3 na = (Rx0_norm + x1_norm).cross(t); const Vec3 nb = (Rx0_norm - x1_norm).cross(t); const Vec3 nprime = na.squaredNorm() >= nb.squaredNorm() ? na.normalized() : nb.normalized(); const Vec3 mprime0 = Rx0 - (Rx0.dot(nprime)) * nprime; const Vec3 mprime1 = x1 - (x1.dot(nprime)) * nprime; return Compute3DPoint(mprime0, mprime1, t, R1, t1, X_euclidean); } bool TriangulateIDWMidpoint( const Mat3 & R0, const Vec3 & t0, const Vec3 & x0, const Mat3 & R1, const Vec3 & t1, const Vec3 & x1, Vec3* X_euclidean ) { // absolute to relative Mat3 R; Vec3 t, Rx0; AbsoluteToRelative(R0, t0, R1, t1, x0, R, t, Rx0); const double p_norm = Rx0.cross(x1).norm(); const double q_norm = Rx0.cross(t).norm(); const double r_norm = x1.cross(t).norm(); // Eq. (10) const auto xprime1 = ( q_norm / (q_norm + r_norm) ) * ( t + (r_norm / p_norm) * (Rx0 + x1) ); // relative to absolute *X_euclidean = R1.transpose() * (xprime1 - t1); // Eq. (7) const Vec3 lambda0_Rx0 = (r_norm / p_norm) * Rx0; const Vec3 lambda1_x1 = (q_norm / p_norm) * x1; // Eq. (9) - test adequation return (t + lambda0_Rx0 - lambda1_x1).squaredNorm() < std::min(std::min( (t + lambda0_Rx0 + lambda1_x1).squaredNorm(), (t - lambda0_Rx0 - lambda1_x1).squaredNorm()), (t - lambda0_Rx0 + lambda1_x1).squaredNorm()); } bool Triangulate2View ( const Mat3 &R0, const Vec3 &t0, const Vec3 &bearing0, const Mat3 &R1, const Vec3 &t1, const Vec3 &bearing1, Vec3 &X, ETriangulationMethod etri_method ) { switch (etri_method) { case ETriangulationMethod::DIRECT_LINEAR_TRANSFORM: return TriangulateDLT(R0, t0, bearing0, R1, t1, bearing1, &X); break; case ETriangulationMethod::L1_ANGULAR: return TriangulateL1Angular(R0, t0, bearing0, R1, t1, bearing1, &X); break; case ETriangulationMethod::LINFINITY_ANGULAR: return TriangulateLInfinityAngular(R0, t0, bearing0, R1, t1, bearing1, &X); break; case ETriangulationMethod::INVERSE_DEPTH_WEIGHTED_MIDPOINT: return TriangulateIDWMidpoint(R0, t0, bearing0, R1, t1, bearing1, &X); break; default: return false; } return false; } } // namespace openMVG
6,290
C++
.cpp
223
25.29148
101
0.661424
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,728
triangulation_test.cpp
openMVG_openMVG/src/openMVG/multiview/triangulation_test.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/multiview/projection.hpp" #include "openMVG/multiview/test_data_sets.hpp" #include "openMVG/multiview/triangulation.hpp" #include "openMVG/numeric/numeric.h" #include "testing/testing.h" using namespace openMVG; TEST(Triangulation, TriangulateDLT) { const NViewDataSet d = NRealisticCamerasRing(2, 12); for (int i = 0; i < d._X.cols(); ++i) { const Vec3 X_gt = d._X.col(i); Vec3 X_estimated = Vec3::Random(); const Vec2 x1 = d._x[0].col(i); const Vec2 x2 = d._x[1].col(i); TriangulateDLT(d.P(0), x1.homogeneous(), d.P(1), x2.homogeneous(), &X_estimated); EXPECT_NEAR(0, DistanceLInfinity(X_estimated, X_gt), 1e-8); X_estimated = Vec3::Random(); TriangulateDLT(d._R[0], d._t[0], d._K[0].inverse() * x1.homogeneous(), d._R[1], d._t[1], d._K[1].inverse() * x2.homogeneous(), &X_estimated); EXPECT_NEAR(0, DistanceLInfinity(X_estimated, X_gt), 1e-8); } } TEST(Triangulation, TriangulateL1Angular) { const NViewDataSet d = NRealisticCamerasRing(2, 12); for (int i = 0; i < d._X.cols(); ++i) { const Vec3 X_gt = d._X.col(i); Vec3 X_estimated; const Vec2 x1 = d._x[0].col(i); const Vec2 x2 = d._x[1].col(i); const bool cheir_ok = TriangulateL1Angular(d._R[0], d._t[0], d._K[0].inverse() * x1.homogeneous(), d._R[1], d._t[1], d._K[1].inverse() * x2.homogeneous(), &X_estimated); EXPECT_TRUE(cheir_ok); EXPECT_NEAR(0, DistanceLInfinity(X_estimated, X_gt), 1e-8); } } TEST(Triangulation, TriangulateLInfinityAngular) { const NViewDataSet d = NRealisticCamerasRing(2, 12); for (int i = 0; i < d._X.cols(); ++i) { const Vec3 X_gt = d._X.col(i); Vec3 X_estimated; const Vec2 x1 = d._x[0].col(i); const Vec2 x2 = d._x[1].col(i); const bool cheir_ok = TriangulateLInfinityAngular(d._R[0], d._t[0], d._K[0].inverse() * x1.homogeneous(), d._R[1], d._t[1], d._K[1].inverse() * x2.homogeneous(), &X_estimated); EXPECT_TRUE(cheir_ok); EXPECT_NEAR(0, DistanceLInfinity(X_estimated, X_gt), 1e-8); } } TEST(Triangulation, TriangulateIDWMidpoint) { const NViewDataSet d = NRealisticCamerasRing(2, 12); for (int i = 0; i < d._X.cols(); ++i) { const Vec3 X_gt = d._X.col(i); Vec3 X_estimated; const Vec2 x1 = d._x[0].col(i); const Vec2 x2 = d._x[1].col(i); const bool cheir_ok = TriangulateIDWMidpoint(d._R[0], d._t[0], d._K[0].inverse() * x1.homogeneous(), d._R[1], d._t[1], d._K[1].inverse() * x2.homogeneous(), &X_estimated); EXPECT_TRUE(cheir_ok); EXPECT_NEAR(0, DistanceLInfinity(X_estimated, X_gt), 1e-8); } } TEST(Triangulation, Factoring) { const NViewDataSet d = NRealisticCamerasRing(2, 12); const std::vector<ETriangulationMethod> triangulation_methods = { ETriangulationMethod::DIRECT_LINEAR_TRANSFORM, ETriangulationMethod::L1_ANGULAR, ETriangulationMethod::LINFINITY_ANGULAR, ETriangulationMethod::INVERSE_DEPTH_WEIGHTED_MIDPOINT }; for (const auto& method_it : triangulation_methods) { for (int i = 0; i < d._X.cols(); ++i) { const Vec3 X_gt = d._X.col(i); Vec3 X_estimated = Vec3::Random(); const Vec2 x1 = d._x[0].col(i); const Vec2 x2 = d._x[1].col(i); const bool cheir_ok = Triangulate2View( d._R[0], d._t[0], d._K[0].inverse() * x1.homogeneous(), d._R[1], d._t[1], d._K[1].inverse() * x2.homogeneous(), X_estimated, method_it); EXPECT_TRUE(cheir_ok); EXPECT_NEAR(0, DistanceLInfinity(X_estimated, X_gt), 1e-8); } } } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */
4,081
C++
.cpp
96
38.354167
180
0.619587
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,736
LiGT_algorithm.cpp
openMVG_openMVG/src/openMVG/multiview/LiGT/LiGT_algorithm.cpp
// This file is part of a pose-only algorithm of Linear Global Translation (LiGT) // Copyright (c) 2022, Qi Cai and Yuanxin Wu // This Source Code Form is subject to the license terms of // Creative Commons Attribution Share Alike 4.0 International. // Details are available at https://choosealicense.com/licenses/cc-by-sa-4.0/ #include <Eigen/Core> #include <Eigen/Dense> #include <Eigen/Sparse> #include <Eigen/SVD> #include <chrono> #ifdef OPENMVG_USE_OPENMP #include <omp.h> #endif #include "LiGT_algorithm.hpp" #include "openMVG/numeric/numeric.h" #include "openMVG/system/logger.hpp" #include "openMVG/system/timer.hpp" #include "third_party/spectra/include/Spectra/SymEigsShiftSolver.h" using namespace Eigen; using namespace std::chrono; using namespace Spectra; namespace LiGT { // ==================== LiGT Problem ======================== LiGTProblem::LiGTProblem() { num_view_ = 0; num_pts_ = 0; num_obs_ = 0; time_use_ = 0; fixed_id_ = 0; min_track_length_ = 2; } void LiGTProblem::CheckTracks(){ OPENMVG_LOG_INFO << "checking tracks information..."; IndexT tmp_num_obs = 0; std::set<ViewId> est_view; for ( PtsId i = 0; i < tracks_.size(); ++i){ const Track& track = tracks_[i].track; for (ObsId j = 0; j < track.size(); ++j){ est_view.insert(track[j].view_id); } tmp_num_obs += track.size(); } // check information if (num_view_ != est_view.size()) { num_view_ = est_view.size(); } if (num_pts_ != tracks_.size()) { num_pts_ = tracks_.size(); } if (num_obs_ != tmp_num_obs) { num_obs_ = tmp_num_obs; } // build estimated view information ViewId id = 0; for ( auto& view_id : est_view){ est_info_.origin_view_ids.emplace_back(view_id); est_info_.estimated_view_ids.emplace_back(id); id ++; } // select the reference view id by the fixed camera id auto& origin_view_id = est_info_.origin_view_ids[0]; for ( ViewId i = 0; i < est_info_.origin_view_ids.size(); ++i){ if ( est_info_.origin_view_ids[i] == fixed_id_){ est_info_.origin_view_ids[0] = est_info_.origin_view_ids[i]; est_info_.origin_view_ids[i] = origin_view_id; } } est_info_.BuildMap(); // update view id in track for ( PtsId i = 0; i < tracks_.size(); ++i){ Track& track = tracks_[i].track; for ( ObsId j = 0; j < track.size(); ++j){ track[j].view_id = est_info_.origin2est_view_ids[track[j].view_id]; } } } void LiGTProblem::RecoverViewIds(){ OPENMVG_LOG_INFO << "recover the estimated view ids into original view ids"; for (ViewId i = 0; i < num_view_; ++i){ const geometry::Pose3 tmp_pose(global_rotations_[i], global_translations_[i]); poses_.insert({est_info_.est2origin_view_ids[i], tmp_pose}); } } void LiGTProblem::IdentifySign(const MatrixXd& A_lr, VectorXd& evectors) { const VectorXd judgeValue = A_lr * evectors; const int positive_count = (judgeValue.array() > 0.0).cast<int>().sum(); const int negative_count = judgeValue.rows() - positive_count; if (positive_count < negative_count) { evectors = -evectors; } } void LiGTProblem::SelectBaseViews(const Track& track, ViewId& lbase_view_id, ViewId& rbase_view_id, ObsId& id_lbase, ObsId& id_rbase){ double best_criterion_value = 0; IndexT track_size = track.size(); // [Step.2 in Pose-only Algorithm]: select the left/right-base views for (ObsId i = 0; i < track_size - 1; ++i) { for (ObsId j = i + 1; j < track_size; ++j) { const ViewId& i_view_id = track[i].view_id; const ViewId& j_view_id = track[j].view_id; const Vector3d& i_coord = track[i].coord; const Vector3d& j_coord = track[j].coord; const Matrix3d& R_i = global_rotations_[i_view_id]; const Matrix3d& R_j = global_rotations_[j_view_id]; const Matrix3d R_ij = R_j * R_i.transpose(); const Vector3d theta_ij = j_coord.cross(R_ij * i_coord); double criterion_value = theta_ij.norm(); if (criterion_value > best_criterion_value) { best_criterion_value = criterion_value; lbase_view_id = track[i].view_id; rbase_view_id = track[j].view_id; id_lbase = i; id_rbase = j; } } } } void LiGTProblem::BuildLTL(Eigen::MatrixXd& LTL, MatrixXd& A_lr){ #ifdef OPENMVG_USE_OPENMP #pragma omp parallel for shared(A_lr, LTL) #endif for (int track_id = 0; track_id < static_cast<int>(tracks_.size()); ++track_id) { const TrackInfo& track_info = tracks_[track_id]; const Track& track = track_info.track; ViewId lbase_view_id = 0; ViewId rbase_view_id = 0; ObsId id_lbase = 0; ObsId id_rbase = 0; // [Step.2 in Pose-only algorithm]: select left/right-base views SelectBaseViews(track, lbase_view_id, rbase_view_id, id_lbase, id_rbase); Eigen::MatrixXd tmp_LiGT_vec = Eigen::MatrixXd::Zero(3, num_view_ * 3); // [Step.3 in Pose-only algorithm]: calculate local L matrix, for (ObsId i = 0; i < track.size(); i++) { ViewId i_view_id = track[i].view_id; // the current view id if (i_view_id != lbase_view_id) { Mat3 xi_cross = CrossProductMatrix(track[i].coord); Mat3 R_li = global_rotations_[i_view_id] * global_rotations_[lbase_view_id].transpose(); Mat3 R_lr = global_rotations_[rbase_view_id] * global_rotations_[lbase_view_id].transpose(); Vec3 tmp_a_lr = CrossProductMatrix(R_lr * track[id_lbase].coord) * track[id_rbase].coord; // a_lr (Row) vector in a_lr * t > 0 Eigen::RowVector3d a_lr = tmp_a_lr.transpose() * CrossProductMatrix(track[id_rbase].coord); // combine all a_lr vectors into a matrix form A, i.e., At > 0 A_lr.row(track_id).block<1, 3>(0, lbase_view_id * 3) = a_lr * global_rotations_[rbase_view_id]; A_lr.row(track_id).block<1, 3>(0, rbase_view_id * 3) = -a_lr * global_rotations_[rbase_view_id]; // theta_lr Vec3 theta_lr_vector = CrossProductMatrix(track[id_rbase].coord) * R_lr * track[id_lbase].coord; double theta_lr = theta_lr_vector.squaredNorm(); // calculate matrix B [rbase_view_id] Eigen::Matrix3d Coefficient_B = xi_cross * R_li * track[id_lbase].coord * a_lr * global_rotations_[rbase_view_id]; // calculate matrix C [i_view_id] Eigen::Matrix3d Coefficient_C = theta_lr * CrossProductMatrix(track[i].coord) * global_rotations_[i_view_id]; // calculate matrix D [lbase_view_id] Eigen::Matrix3d Coefficient_D = -(Coefficient_B + Coefficient_C); // calculate temp matrix L for a single 3D matrix tmp_LiGT_vec.setZero(); tmp_LiGT_vec.block<3, 3>(0, rbase_view_id * 3) += Coefficient_B; tmp_LiGT_vec.block<3, 3>(0, i_view_id * 3) += Coefficient_C; tmp_LiGT_vec.block<3, 3>(0, lbase_view_id * 3) += Coefficient_D; // calculate LtL submodule Eigen::MatrixXd LTL_l_row = Coefficient_D.transpose() * tmp_LiGT_vec; Eigen::MatrixXd LTL_r_row = Coefficient_B.transpose() * tmp_LiGT_vec; Eigen::MatrixXd LTL_i_row = Coefficient_C.transpose() * tmp_LiGT_vec; // assignment for LtL (except for the reference view id) #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { if(lbase_view_id > 0 ) LTL.middleRows<3>(lbase_view_id * 3 - 3) += LTL_l_row.rightCols(LTL_l_row.cols() - 3); if(rbase_view_id > 0 ) LTL.middleRows<3>(rbase_view_id * 3 - 3) += LTL_r_row.rightCols(LTL_r_row.cols() - 3); if(i_view_id > 0 ) LTL.middleRows<3>(i_view_id * 3 - 3) += LTL_i_row.rightCols(LTL_i_row.cols() - 3); } } } } } bool LiGTProblem::SolveLiGT(const Eigen::MatrixXd& LTL, VectorXd& evectors){ // ========================= Solve Problem by Eigen's SVD ======================= // JacobiSVD<Eigen::MatrixXd> svd(LTL, ComputeFullU | ComputeFullV); // if (svd.info() != Eigen::Success) // OPENMVG_LOG_ERROR << "SVD solver failure - expect to have invalid output"; // MatrixXd V = svd.matrixV(); // evectors.bottomRows(V.rows()) = V.col(V.cols() - 1); // ========================= Solve Problem by Spectra's Eigs ======================= // Construct matrix operation object using the wrapper class DenseSymShiftSolve<double> op(LTL); // Construct eigen solver object with shift 0 // This will find eigenvalues that are closest to 0 SymEigsShiftSolver<DenseSymShiftSolve<double>> eigs(op, 1, 8, 0.0); eigs.init(); eigs.compute(SortRule::LargestMagn); if (eigs.info() != CompInfo::Successful) { OPENMVG_LOG_ERROR << " SymEigsShiftSolver failure - expect to have invalid output"; return false; } const Eigen::VectorXd evalues = eigs.eigenvalues(); OPENMVG_LOG_INFO << "Eigenvalues found: " << evalues.transpose(); evectors.bottomRows( 3 * num_view_ - 3) = eigs.eigenvectors(); return true; } bool LiGTProblem::Solution() { PrintCopyright(); OPENMVG_LOG_INFO <<"\n************ LiGT Solve Summary **************\n" << "num_view = " << num_view_ << "; num_pts = " << num_pts_ << "; num_obs = " << num_obs_; // start time clock openMVG::system::Timer timer; // allocate memory for LTL matrix where Lt=0 Eigen::MatrixXd LTL = Eigen::MatrixXd::Zero(num_view_ * 3-3, num_view_ * 3-3); // use A_lr * t > 0 to identify the correct sign of the translation result Eigen::MatrixXd A_lr = Eigen::MatrixXd::Zero(tracks_.size(), 3 * num_view_); // construct LTL and A_lr matrix from 3D points BuildLTL(LTL, A_lr); //[Step.4 in Pose-only Algorithm]: obtain the translation solution by using SVD VectorXd evectors = VectorXd::Zero( 3 * num_view_); if (!SolveLiGT(LTL, evectors)) { return false; } //[Step.5 in Pose-only Algorithm]: identify the right global translation solution IdentifySign(A_lr, evectors); // algorithm time cost const double duration = timer.elapsedMs(); OPENMVG_LOG_INFO << ">> time for the LiGT algorithm: " << duration << " ms" << "\n==============================================================="; time_use_ = duration; // (optional) transform solution evectors into global_translations_ global_translations_.clear(); global_translations_.resize(num_view_); for (ViewId i = 0; i < num_view_; ++i) { global_translations_[i] = evectors.middleRows<3>(3*i); } // (optional) translation recovery RecoverViewIds(); return true; } Tracks LiGTProblem::GetTracks(){ return tracks_; } Poses LiGTProblem::GetPoses(){ return poses_; } Rotations LiGTProblem::GetRotations(){ return global_rotations_; } void LiGTProblem::PrintCopyright() const{ OPENMVG_LOG_INFO << "\n===============================================================\n" << " The LiGT Algorithm (Version 1.1) for global translation\n" << "[Conditions of Use] The LiGT algorithm is distributed under the License\n" << "of Attribution-ShareAlike 4.0 International\n" << "(https://creativecommons.org/licenses/by-sa/4.0/).\n" << "If you use it for a publication, please see [Notes] in header file.\n" << "---------------------------------------------------------------"; } }
11,440
C++
.cpp
277
35.891697
104
0.619417
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,737
LiGT_algorithm_converter.cpp
openMVG_openMVG/src/openMVG/multiview/LiGT/LiGT_algorithm_converter.cpp
// This file is part of a pose-only algorithm of Linear Global Translation (LiGT) // Copyright (c) 2022, Qi Cai and Yuanxin Wu // This Source Code Form is subject to the license terms of // Creative Commons Attribution Share Alike 4.0 International. // Details are available at https://choosealicense.com/licenses/cc-by-sa-4.0/ #include <Eigen/Core> #include <Eigen/Dense> #include <Eigen/Sparse> #include <Eigen/SVD> #include <chrono> #include <map> #include "LiGT_algorithm_converter.hpp" #include "openMVG/cameras/cameras.hpp" using namespace Eigen; using namespace std::chrono; using namespace openMVG; using namespace openMVG::matching; using namespace openMVG::sfm; using namespace openMVG::tracks; using namespace openMVG::cameras; namespace LiGT { LiGTBuilder::LiGTBuilder(const Features_Provider* features_provider, const PairWiseMatches& pairWise_matches, const SfM_Data& sfm_data, const Hash_Map<IndexT, Mat3>& map_globalR, const int min_track_length, const int fixed_id){ // build observation and bearing vectors BuildTracks(features_provider, pairWise_matches, sfm_data); // load global rotations MapR2Rotations(map_globalR); time_use_ = 0; fixed_id_ = fixed_id; min_track_length_ = min_track_length; // check tracks and build estimated information [EstInfo] CheckTracks(); } void LiGTBuilder::MapR2Rotations(const Hash_Map<IndexT, Mat3>& map_globalR){ std::map<IndexT,Matrix3d> tmp_map_R; // sort by the key value (ViewId) for (auto& R: map_globalR){ tmp_map_R.insert({R.first, R.second}); } // generate global rotations global_rotations_.clear(); for (auto& R: tmp_map_R){ global_rotations_.emplace_back(R.second); } } void LiGTBuilder::BuildTracks(const Features_Provider* features_provider, const PairWiseMatches& pairWise_matches, const SfM_Data& sfm_data){ // Build OpenMVG tracks tracks::STLMAPTracks map_tracks; { tracks::TracksBuilder tracksBuilder; tracksBuilder.Build(pairWise_matches); tracksBuilder.Filter(min_track_length_); tracksBuilder.ExportToSTL(map_tracks); } tracks_.clear(); // For every track add the observations to LiGT Tracks // - views and feature positions that see this landmark tracks_.reserve(map_tracks.size()); IndexT trackId(0); for (const auto& trackIt : map_tracks) { TrackInfo track_info; const submapTrack& track = trackIt.second; track_info.track.reserve(track.size()); for (const auto& it : track) { const size_t imaIndex = it.first; const size_t featIndex = it.second; const auto& pt = features_provider->feats_per_view.at(imaIndex)[featIndex]; const View* view = sfm_data.views.at(imaIndex).get(); const IntrinsicBase* cam = sfm_data.GetIntrinsics().at(view->id_intrinsic).get(); const Vec2 x = cam->get_ud_pixel(pt.coords().cast<double>()); ObsInfo obs_info; obs_info.view_id = imaIndex; obs_info.pts_id = trackId; obs_info.coord = (*cam)(x); track_info.track.emplace_back(obs_info); } tracks_.emplace_back(track_info); ++trackId; } }; }
3,190
C++
.cpp
89
31.516854
87
0.711964
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,738
Schur.cpp
openMVG_openMVG/src/third_party/spectra/test/Schur.cpp
// Test ../include/Spectra/LinAlg/UpperHessenbergSchur.h #include <iostream> #include <Eigen/Core> #include <Spectra/LinAlg/UpperHessenbergSchur.h> using namespace Spectra; #include "catch.hpp" using Matrix = Eigen::MatrixXd; using Vector = Eigen::VectorXd; // Schur decomposition on an upper Hessenberg matrix void run_test(const Matrix& A) { // Spectra implementation UpperHessenbergSchur<double> decomp(A); const Matrix& matT = decomp.matrix_T(); const Matrix& matU = decomp.matrix_U(); // Test whether T is upper Hessenberg Matrix lowerT = matT.triangularView<Eigen::StrictlyLower>(); lowerT.diagonal(-1).setZero(); INFO("||lower T||_inf = " << lowerT.cwiseAbs().maxCoeff()); REQUIRE(lowerT.cwiseAbs().maxCoeff() == Approx(0.0).margin(1e-16)); // Test whether Q is orthonormal constexpr double tol = 1e-12; const int n = A.rows(); Matrix I = Matrix::Identity(n, n); Matrix resid1 = matU.transpose() * matU - I; Matrix resid2 = matU * matU.transpose() - I; INFO("||U'U - I||_inf = " << resid1.cwiseAbs().maxCoeff()); REQUIRE(resid1.cwiseAbs().maxCoeff() == Approx(0.0).margin(tol)); INFO("||UU' - I||_inf = " << resid2.cwiseAbs().maxCoeff()); REQUIRE(resid2.cwiseAbs().maxCoeff() == Approx(0.0).margin(tol)); // Test whether AU=UT Matrix resid3 = A * matU - matU * matT; INFO("||AU - UT||_inf = " << resid3.cwiseAbs().maxCoeff()); REQUIRE(resid3.cwiseAbs().maxCoeff() == Approx(0.0).margin(tol)); } Matrix gen_upper_hessenberg_mat(int n) { std::srand(123); Matrix A = Matrix::Random(n, n); A.triangularView<Eigen::StrictlyLower>().setZero(); A.diagonal(-1).array() = Vector::Random(n - 1).array(); return A; } TEST_CASE("Schur decomposition of upper Hessenberg matrix [10x10]", "[Schur]") { Matrix A = gen_upper_hessenberg_mat(10); run_test(A); } TEST_CASE("Schur decomposition of upper Hessenberg matrix [100x100]", "[Schur]") { Matrix A = gen_upper_hessenberg_mat(100); run_test(A); } TEST_CASE("Schur decomposition of upper Hessenberg matrix [500x500]", "[Schur]") { Matrix A = gen_upper_hessenberg_mat(500); run_test(A); }
2,177
C++
.cpp
58
34
80
0.672676
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,739
SparseGenMatProd.cpp
openMVG_openMVG/src/third_party/spectra/test/SparseGenMatProd.cpp
#include <Spectra/MatOp/SparseGenMatProd.h> #include <Eigen/Core> #include <Eigen/SparseCore> #include <Eigen/Dense> using namespace Spectra; #include "catch.hpp" using Eigen::Index; template <typename TestType> using Matrix = Eigen::Matrix<TestType, Eigen::Dynamic, Eigen::Dynamic>; template <typename T> Eigen::SparseMatrix<T> generate_random_sparse(Index rows, Index cols) { std::default_random_engine gen; std::uniform_real_distribution<T> dist(0.0, 1.0); std::vector<Eigen::Triplet<T>> tripletVector; for (int i = 0; i < rows; ++i) for (int j = 0; j < cols; ++j) { auto v_ij = dist(gen); if (v_ij < 0.5) { // if larger than treshold, insert it tripletVector.push_back(Eigen::Triplet<T>(i, j, v_ij)); } } Eigen::SparseMatrix<T> mat(rows, cols); // create the matrix mat.setFromTriplets(tripletVector.begin(), tripletVector.end()); return mat; } TEMPLATE_TEST_CASE("matrix operations [100x100]", "[SparseGenMatProd]", float, double) { std::srand(123); constexpr Index n = 100; Eigen::SparseMatrix<TestType> mat1 = generate_random_sparse<TestType>(n, n); Matrix<TestType> mat2 = Matrix<TestType>::Random(n, n); SparseGenMatProd<TestType> sparse1(mat1); Matrix<TestType> xs = sparse1 * mat2; Matrix<TestType> ys = mat1 * mat2; INFO("The matrix-matrix product must be the same as in eigen.") REQUIRE(xs.isApprox(ys)); INFO("The accesor operator must produce the same element as in eigen") REQUIRE(mat1.coeff(45, 22) == sparse1(45, 22)); }
1,631
C++
.cpp
44
31.704545
86
0.662222
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,740
SymGEigsShift.cpp
openMVG_openMVG/src/third_party/spectra/test/SymGEigsShift.cpp
#include <Eigen/Core> #include <Eigen/SparseCore> #include <iostream> #include <random> // Requires C++ 11 #include <Spectra/SymGEigsShiftSolver.h> #include <Spectra/MatOp/SymShiftInvert.h> #include <Spectra/MatOp/DenseSymMatProd.h> #include <Spectra/MatOp/SparseSymMatProd.h> using namespace Spectra; #include "catch.hpp" using Matrix = Eigen::MatrixXd; using Vector = Eigen::VectorXd; using SpMatrix = Eigen::SparseMatrix<double>; // Generate random sparse matrix SpMatrix sprand(int size, double prob = 0.5) { SpMatrix mat(size, size); std::default_random_engine gen; gen.seed(0); std::uniform_real_distribution<double> distr(0.0, 1.0); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (distr(gen) < prob) mat.insert(i, j) = distr(gen) - 0.5; } } return mat; } // Generate data for testing void gen_dense_data(int n, Matrix& A, Matrix& B) { // Eigen solver only uses the lower triangle of A, // so we don't need to make A symmetric here A = Matrix::Random(n, n); B = A.transpose() * A; // To make sure B is positive definite B.diagonal() += Eigen::VectorXd::Random(n).cwiseAbs(); } void gen_sparse_data(int n, SpMatrix& A, SpMatrix& B, double prob = 0.1) { // Eigen solver only uses the lower triangle of A, // so we don't need to make A symmetric here A = sprand(n, prob); B = A.transpose() * A; // To make sure B is positive definite for (int i = 0; i < n; i++) B.coeffRef(i, i) += 0.1; } template <typename TypeA, typename TypeB, typename Solver> void run_test(const TypeA& A, const TypeB& B, Solver& eigs, SortRule selection, bool allow_fail = false) { eigs.init(); // maxit = 100 to reduce running time for failed cases int nconv = eigs.compute(selection, 100); int niter = eigs.num_iterations(); int nops = eigs.num_operations(); if (allow_fail && eigs.info() != CompInfo::Successful) { WARN("FAILED on this test"); std::cout << "nconv = " << nconv << std::endl; std::cout << "niter = " << niter << std::endl; std::cout << "nops = " << nops << std::endl; return; } else { INFO("nconv = " << nconv); INFO("niter = " << niter); INFO("nops = " << nops); REQUIRE(eigs.info() == CompInfo::Successful); } Vector evals = eigs.eigenvalues(); Matrix evecs = eigs.eigenvectors(); Matrix resid = A.template selfadjointView<Eigen::Lower>() * evecs - B.template selfadjointView<Eigen::Lower>() * evecs * evals.asDiagonal(); const double err = resid.array().abs().maxCoeff(); INFO("||AU - UD||_inf = " << err); REQUIRE(err == Approx(0.0).margin(1e-9)); } template <typename TypeA, typename TypeB, typename Solver> void run_test_sets(const TypeA& A, const TypeB& B, Solver& eigs) { SECTION("Largest Magnitude") { run_test(A, B, eigs, SortRule::LargestMagn); } SECTION("Largest Value") { run_test(A, B, eigs, SortRule::LargestAlge); } SECTION("Smallest Magnitude") { run_test(A, B, eigs, SortRule::SmallestMagn, true); } SECTION("Smallest Value") { run_test(A, B, eigs, SortRule::SmallestAlge); } SECTION("Both Ends") { run_test(A, B, eigs, SortRule::BothEnds); } } // ======================== Shift-and-invert mode ======================== // // A is sparse, B is sparse TEST_CASE("Generalized eigensolver of symmetric real matrices [shift-invert, ss, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix A, B; gen_sparse_data(100, A, B, 0.1); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Sparse, Eigen::Sparse>; using BOpType = SparseSymMatProd<double>; OpType op(A, B); BOpType Bop(B); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::ShiftInvert> eigs(op, Bop, k, m, sigma); run_test_sets(A, B, eigs); } // A is sparse, B is dense TEST_CASE("Generalized eigensolver of symmetric real matrices [shift-invert, sd, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix As, Bs; gen_sparse_data(100, As, Bs, 0.1); Matrix Ad, Bd; gen_dense_data(100, Ad, Bd); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Sparse, Eigen::Dense>; using BOpType = DenseSymMatProd<double>; OpType op(As, Bd); BOpType Bop(Bd); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::ShiftInvert> eigs(op, Bop, k, m, sigma); run_test_sets(As, Bd, eigs); } // A is dense, B is sparse TEST_CASE("Generalized eigensolver of symmetric real matrices [shift-invert, ds, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix As, Bs; gen_sparse_data(100, As, Bs, 0.1); Matrix Ad, Bd; gen_dense_data(100, Ad, Bd); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Dense, Eigen::Sparse>; using BOpType = SparseSymMatProd<double>; OpType op(Ad, Bs); BOpType Bop(Bs); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::ShiftInvert> eigs(op, Bop, k, m, sigma); run_test_sets(Ad, Bs, eigs); } // A is dense, B is dense TEST_CASE("Generalized eigensolver of symmetric real matrices [shift-invert, dd, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle Matrix A, B; gen_dense_data(100, A, B); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Dense, Eigen::Dense>; using BOpType = DenseSymMatProd<double>; OpType op(A, B); BOpType Bop(B); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::ShiftInvert> eigs(op, Bop, k, m, sigma); run_test_sets(A, B, eigs); } // ======================== Buckling mode ======================== // // K is sparse, KG is sparse TEST_CASE("Generalized eigensolver of symmetric real matrices [buckling, ss, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix K, KG; gen_sparse_data(100, KG, K, 0.1); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Sparse, Eigen::Sparse>; using BOpType = SparseSymMatProd<double>; OpType op(K, KG); BOpType Bop(K); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::Buckling> eigs(op, Bop, k, m, sigma); run_test_sets(K, KG, eigs); } // K is sparse, KG is dense TEST_CASE("Generalized eigensolver of symmetric real matrices [buckling, sd, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix Ks, KGs; gen_sparse_data(100, KGs, Ks, 0.1); Matrix Kd, KGd; gen_dense_data(100, KGd, Kd); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Sparse, Eigen::Dense>; using BOpType = SparseSymMatProd<double>; OpType op(Ks, KGd); BOpType Bop(Ks); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::Buckling> eigs(op, Bop, k, m, sigma); run_test_sets(Ks, KGd, eigs); } // K is dense, KG is sparse TEST_CASE("Generalized eigensolver of symmetric real matrices [buckling, ds, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix Ks, KGs; gen_sparse_data(100, KGs, Ks, 0.1); Matrix Kd, KGd; gen_dense_data(100, KGd, Kd); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Dense, Eigen::Sparse>; using BOpType = DenseSymMatProd<double>; OpType op(Kd, KGs); BOpType Bop(Kd); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::Buckling> eigs(op, Bop, k, m, sigma); run_test_sets(Kd, KGs, eigs); } // K is dense, KG is dense TEST_CASE("Generalized eigensolver of symmetric real matrices [buckling, dd, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle Matrix K, KG; gen_dense_data(100, KG, K); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Dense, Eigen::Dense>; using BOpType = DenseSymMatProd<double>; OpType op(K, KG); BOpType Bop(K); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::Buckling> eigs(op, Bop, k, m, sigma); run_test_sets(K, KG, eigs); } // ======================== Cayley mode ======================== // // A is sparse, B is sparse TEST_CASE("Generalized eigensolver of symmetric real matrices [cayley, ss, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix A, B; gen_sparse_data(100, A, B, 0.1); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Sparse, Eigen::Sparse>; using BOpType = SparseSymMatProd<double>; OpType op(A, B); BOpType Bop(B); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::Cayley> eigs(op, Bop, k, m, sigma); run_test_sets(A, B, eigs); } // A is sparse, B is dense TEST_CASE("Generalized eigensolver of symmetric real matrices [cayley, sd, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix As, Bs; gen_sparse_data(100, As, Bs, 0.1); Matrix Ad, Bd; gen_dense_data(100, Ad, Bd); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Sparse, Eigen::Dense>; using BOpType = DenseSymMatProd<double>; OpType op(As, Bd); BOpType Bop(Bd); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::Cayley> eigs(op, Bop, k, m, sigma); run_test_sets(As, Bd, eigs); } // A is dense, B is sparse TEST_CASE("Generalized eigensolver of symmetric real matrices [cayley, ds, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix As, Bs; gen_sparse_data(100, As, Bs, 0.1); Matrix Ad, Bd; gen_dense_data(100, Ad, Bd); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Dense, Eigen::Sparse>; using BOpType = SparseSymMatProd<double>; OpType op(Ad, Bs); BOpType Bop(Bs); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::Cayley> eigs(op, Bop, k, m, sigma); run_test_sets(Ad, Bs, eigs); } // A is dense, B is dense TEST_CASE("Generalized eigensolver of symmetric real matrices [cayley, dd, 100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle Matrix A, B; gen_dense_data(100, A, B); int k = 10; int m = 20; double sigma = 1.2345; using OpType = SymShiftInvert<double, Eigen::Dense, Eigen::Dense>; using BOpType = DenseSymMatProd<double>; OpType op(A, B); BOpType Bop(B); SymGEigsShiftSolver<OpType, BOpType, GEigsMode::Cayley> eigs(op, Bop, k, m, sigma); run_test_sets(A, B, eigs); }
11,219
C++
.cpp
324
30.12963
106
0.643966
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,742
DenseGenMatProd.cpp
openMVG_openMVG/src/third_party/spectra/test/DenseGenMatProd.cpp
#include <Spectra/MatOp/DenseGenMatProd.h> #include <Eigen/Dense> using namespace Spectra; #include "catch.hpp" using Eigen::Matrix; using Eigen::Index; TEMPLATE_TEST_CASE("matrix operations", "[DenseGenMatProd]", float, double) { std::srand(123); constexpr Index n = 100; Matrix<TestType, -1, -1> mat1 = Matrix<TestType, -1, -1>::Random(n, n); Matrix<TestType, -1, -1> mat2 = Matrix<TestType, -1, -1>::Random(n, n); DenseGenMatProd<TestType> dense1(mat1); Matrix<TestType, -1, -1> xs = dense1 * mat2; Matrix<TestType, -1, -1> ys = mat1 * mat2; INFO("The matrix-matrix product must be the same as in eigen.") REQUIRE(xs.isApprox(ys)); INFO("The accesor operator must produce the same element as in eigen") REQUIRE(mat1(23, 87) == dense1(23, 87)); }
801
C++
.cpp
20
36.45
75
0.684347
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,743
SymGEigsCholesky.cpp
openMVG_openMVG/src/third_party/spectra/test/SymGEigsCholesky.cpp
#include <Eigen/Core> #include <Eigen/SparseCore> #include <iostream> #include <type_traits> #include <random> // Requires C++ 11 #include <Spectra/SymGEigsSolver.h> #include <Spectra/MatOp/DenseSymMatProd.h> #include <Spectra/MatOp/DenseCholesky.h> #include <Spectra/MatOp/SparseSymMatProd.h> #include <Spectra/MatOp/SparseCholesky.h> using namespace Spectra; #include "catch.hpp" using Matrix = Eigen::MatrixXd; using Vector = Eigen::VectorXd; using SpMatrix = Eigen::SparseMatrix<double>; // Generate random sparse matrix SpMatrix sprand(int size, double prob = 0.5) { SpMatrix mat(size, size); std::default_random_engine gen; gen.seed(0); std::uniform_real_distribution<double> distr(0.0, 1.0); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (distr(gen) < prob) mat.insert(i, j) = distr(gen) - 0.5; } } return mat; } // Generate data for testing void gen_dense_data(int n, Matrix& A, Matrix& B) { Matrix M = Eigen::MatrixXd::Random(n, n); A = M + M.transpose(); B = M.transpose() * M; // To make sure B is positive definite B.diagonal() += Eigen::VectorXd::Random(n).cwiseAbs(); } void gen_sparse_data(int n, SpMatrix& A, SpMatrix& B, double prob = 0.1) { // Eigen solver only uses the lower triangle of A, // so we don't need to make A symmetric here. A = sprand(n, prob); B = A.transpose() * A; // To make sure B is positive definite for (int i = 0; i < n; i++) B.coeffRef(i, i) += 0.1; } template <typename MatType, typename Solver> void run_test(const MatType& A, const MatType& B, Solver& eigs, SortRule selection, bool allow_fail = false) { eigs.init(); // maxit = 300 to reduce running time for failed cases int nconv = eigs.compute(selection, 300); int niter = eigs.num_iterations(); int nops = eigs.num_operations(); if (allow_fail && eigs.info() != CompInfo::Successful) { WARN("FAILED on this test"); std::cout << "nconv = " << nconv << std::endl; std::cout << "niter = " << niter << std::endl; std::cout << "nops = " << nops << std::endl; return; } else { INFO("nconv = " << nconv); INFO("niter = " << niter); INFO("nops = " << nops); REQUIRE(eigs.info() == CompInfo::Successful); } Vector evals = eigs.eigenvalues(); Matrix evecs = eigs.eigenvectors(); Matrix resid = A.template selfadjointView<Eigen::Lower>() * evecs - B.template selfadjointView<Eigen::Lower>() * evecs * evals.asDiagonal(); const double err = resid.array().abs().maxCoeff(); INFO("||AU - BUD||_inf = " << err); REQUIRE(err == Approx(0.0).margin(1e-9)); } template <typename MatType> void run_test_sets(const MatType& A, const MatType& B, int k, int m) { constexpr bool is_dense = std::is_same<MatType, Matrix>::value; using DenseOp = DenseSymMatProd<double>; using SparseOp = SparseSymMatProd<double>; using OpType = typename std::conditional<is_dense, DenseOp, SparseOp>::type; using DenseBOp = DenseCholesky<double>; using SparseBOp = SparseCholesky<double>; using BOpType = typename std::conditional<is_dense, DenseBOp, SparseBOp>::type; OpType op(A); BOpType Bop(B); // Make sure B is positive definite and the decomposition is successful REQUIRE(Bop.info() == CompInfo::Successful); SymGEigsSolver<OpType, BOpType, GEigsMode::Cholesky> eigs(op, Bop, k, m); SECTION("Largest Magnitude") { run_test(A, B, eigs, SortRule::LargestMagn); } SECTION("Largest Value") { run_test(A, B, eigs, SortRule::LargestAlge); } SECTION("Smallest Magnitude") { run_test(A, B, eigs, SortRule::SmallestMagn, true); } SECTION("Smallest Value") { run_test(A, B, eigs, SortRule::SmallestAlge); } SECTION("Both Ends") { run_test(A, B, eigs, SortRule::BothEnds); } } TEST_CASE("Generalized eigensolver of symmetric real matrix [10x10]", "[geigs_sym]") { std::srand(123); Matrix A, B; gen_dense_data(10, A, B); int k = 3; int m = 6; run_test_sets(A, B, k, m); } TEST_CASE("Generalized eigensolver of symmetric real matrix [100x100]", "[geigs_sym]") { std::srand(123); Matrix A, B; gen_dense_data(100, A, B); int k = 10; int m = 20; run_test_sets(A, B, k, m); } TEST_CASE("Generalized eigensolver of symmetric real matrix [1000x1000]", "[geigs_sym]") { std::srand(123); Matrix A, B; gen_dense_data(1000, A, B); int k = 20; int m = 50; run_test_sets(A, B, k, m); } TEST_CASE("Generalized eigensolver of sparse symmetric real matrix [10x10]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix A, B; gen_sparse_data(10, A, B, 0.5); int k = 3; int m = 6; run_test_sets(A, B, k, m); } TEST_CASE("Generalized eigensolver of sparse symmetric real matrix [100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix A, B; gen_sparse_data(100, A, B, 0.1); int k = 10; int m = 20; run_test_sets(A, B, k, m); } TEST_CASE("Generalized eigensolver of sparse symmetric real matrix [1000x1000]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix A, B; gen_sparse_data(1000, A, B, 0.01); int k = 20; int m = 50; run_test_sets(A, B, k, m); }
5,551
C++
.cpp
175
27.16
108
0.633028
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,744
DavidsonSymEigs.cpp
openMVG_openMVG/src/third_party/spectra/test/DavidsonSymEigs.cpp
#include <Eigen/Core> #include <Eigen/SparseCore> #include <Spectra/DavidsonSymEigsSolver.h> #include <Spectra/MatOp/DenseSymMatProd.h> #include <Spectra/MatOp/SparseSymMatProd.h> using namespace Spectra; #include "catch.hpp" template <typename T> using Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>; template <typename T> using Vector = Eigen::Matrix<T, Eigen::Dynamic, 1>; template <typename T> using SpMatrix = Eigen::SparseMatrix<T>; // Traits to obtain operation type from matrix type template <typename MatType> struct OpTypeTrait { using Scalar = typename MatType::Scalar; using OpType = DenseSymMatProd<Scalar>; }; template <typename T> struct OpTypeTrait<SpMatrix<T>> { using OpType = SparseSymMatProd<T>; }; // Generate data for testing template <typename Matrix> Matrix gen_sym_data_dense(int n) { Matrix mat = 0.03 * Matrix::Random(n, n); Matrix mat1 = mat + mat.transpose(); for (Eigen::Index i = 0; i < n; i++) { mat1(i, i) += i + 1; } return mat1; } template <typename SpMatrix> SpMatrix gen_sym_data_sparse(int n) { // Eigen solver only uses the lower triangle of mat, // so we don't need to make mat symmetric here. double prob = 0.5; SpMatrix mat(n, n); std::default_random_engine gen; gen.seed(0); std::uniform_real_distribution<double> distr(0.0, 1.0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (distr(gen) < prob) mat.insert(i, j) = 0.1 * (distr(gen) - 0.5); if (i == j) { mat.coeffRef(i, j) = i + 1; } } } return mat; } template <typename MatType> void run_test(const MatType& mat, int nev, SortRule selection) { using OpType = typename OpTypeTrait<MatType>::OpType; OpType op(mat); DavidsonSymEigsSolver<OpType> eigs(op, nev); int nconv = eigs.compute(selection); int niter = eigs.num_iterations(); REQUIRE(nconv == nev); INFO("nconv = " << nconv); INFO("niter = " << niter); REQUIRE(eigs.info() == CompInfo::Successful); using T = typename OpType::Scalar; Vector<T> evals = eigs.eigenvalues(); Matrix<T> evecs = eigs.eigenvectors(); Matrix<T> resid = op * evecs - evecs * evals.asDiagonal(); const T err = resid.array().abs().maxCoeff(); INFO("||AU - UD||_inf = " << err); REQUIRE(err < 100 * Eigen::NumTraits<T>::dummy_precision()); } template <typename MatType> void run_test_set(const MatType& mat, int k) { SECTION("Largest Value") { run_test<MatType>(mat, k, SortRule::LargestAlge); } SECTION("Smallest Value") { run_test<MatType>(mat, k, SortRule::SmallestAlge); } } TEMPLATE_TEST_CASE("Davidson Solver of dense symmetric real matrix [1000x1000]", "", double) { std::srand(123); const Matrix<TestType> A = gen_sym_data_dense<Matrix<TestType>>(1000); int k = 10; run_test_set<Matrix<TestType>>(A, k); } TEMPLATE_TEST_CASE("Davidson Solver of sparse symmetric real matrix [1000x1000]", "", double) { std::srand(123); int k = 10; const SpMatrix<TestType> A = gen_sym_data_sparse<SpMatrix<TestType>>(1000); run_test_set<SpMatrix<TestType>>(A, k); }
3,253
C++
.cpp
107
26.17757
93
0.651646
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,745
GenEigsComplexShift.cpp
openMVG_openMVG/src/third_party/spectra/test/GenEigsComplexShift.cpp
#include <Eigen/Core> #include <Eigen/SparseCore> #include <iostream> #include <type_traits> #include <random> // Requires C++ 11 #include <Spectra/GenEigsComplexShiftSolver.h> #include <Spectra/MatOp/DenseGenComplexShiftSolve.h> #include <Spectra/MatOp/SparseGenComplexShiftSolve.h> using namespace Spectra; #include "catch.hpp" using Matrix = Eigen::MatrixXd; using Vector = Eigen::VectorXd; using ComplexMatrix = Eigen::MatrixXcd; using ComplexVector = Eigen::VectorXcd; using SpMatrix = Eigen::SparseMatrix<double>; // Generate random sparse matrix SpMatrix gen_sparse_data(int n, double prob = 0.5) { SpMatrix mat(n, n); std::default_random_engine gen; gen.seed(0); std::uniform_real_distribution<double> distr(0.0, 1.0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (distr(gen) < prob) mat.insert(i, j) = distr(gen) - 0.5; } } return mat; } template <typename MatType, typename Solver> void run_test(const MatType& mat, Solver& eigs, SortRule selection, bool allow_fail = false) { eigs.init(); // maxit = 100 to reduce running time for failed cases int nconv = eigs.compute(selection, 100); int niter = eigs.num_iterations(); int nops = eigs.num_operations(); if (allow_fail && eigs.info() != CompInfo::Successful) { WARN("FAILED on this test"); std::cout << "nconv = " << nconv << std::endl; std::cout << "niter = " << niter << std::endl; std::cout << "nops = " << nops << std::endl; return; } else { INFO("nconv = " << nconv); INFO("niter = " << niter); INFO("nops = " << nops); REQUIRE(eigs.info() == CompInfo::Successful); } ComplexVector evals = eigs.eigenvalues(); ComplexMatrix evecs = eigs.eigenvectors(); ComplexMatrix resid = mat * evecs - evecs * evals.asDiagonal(); const double err = resid.array().abs().maxCoeff(); INFO("||AU - UD||_inf = " << err); INFO("||AU - UD||_2 colwise = " << resid.colwise().norm()); REQUIRE(err == Approx(0.0).margin(1e-8)); } template <typename MatType> void run_test_sets(const MatType& A, int k, int m, double sigmar, double sigmai) { constexpr bool is_dense = std::is_same<MatType, Matrix>::value; using DenseOp = DenseGenComplexShiftSolve<double>; using SparseOp = SparseGenComplexShiftSolve<double>; using OpType = typename std::conditional<is_dense, DenseOp, SparseOp>::type; OpType op(A); GenEigsComplexShiftSolver<OpType> eigs(op, k, m, sigmar, sigmai); SECTION("Largest Magnitude") { run_test(A, eigs, SortRule::LargestMagn); } SECTION("Largest Real Part") { run_test(A, eigs, SortRule::LargestReal); } SECTION("Largest Imaginary Part") { run_test(A, eigs, SortRule::LargestImag); } SECTION("Smallest Magnitude") { run_test(A, eigs, SortRule::SmallestMagn, true); } SECTION("Smallest Real Part") { run_test(A, eigs, SortRule::SmallestReal); } SECTION("Smallest Imaginary Part") { run_test(A, eigs, SortRule::SmallestImag, true); } } TEST_CASE("Eigensolver of general real matrix [10x10]", "[eigs_gen]") { std::srand(123); const Matrix A = Eigen::MatrixXd::Random(10, 10); int k = 3; int m = 8; double sigmar = 2.0; double sigmai = 1.0; run_test_sets(A, k, m, sigmar, sigmai); } TEST_CASE("Eigensolver of general real matrix [100x100]", "[eigs_gen]") { std::srand(123); const Matrix A = Eigen::MatrixXd::Random(100, 100); int k = 10; int m = 20; double sigmar = 20.0; double sigmai = 10.0; run_test_sets(A, k, m, sigmar, sigmai); } TEST_CASE("Eigensolver of general real matrix [1000x1000]", "[eigs_gen]") { std::srand(123); const Matrix A = Eigen::MatrixXd::Random(1000, 1000); int k = 20; int m = 50; double sigmar = 200.0; double sigmai = 100.0; run_test_sets(A, k, m, sigmar, sigmai); } TEST_CASE("Eigensolver of sparse real matrix [10x10]", "[eigs_gen]") { std::srand(123); const SpMatrix A = gen_sparse_data(10, 0.5); int k = 3; int m = 6; double sigmar = 2.0; double sigmai = 1.0; run_test_sets(A, k, m, sigmar, sigmai); } TEST_CASE("Eigensolver of sparse real matrix [100x100]", "[eigs_gen]") { std::srand(123); const SpMatrix A = gen_sparse_data(100, 0.1); int k = 10; int m = 30; double sigmar = 20.0; double sigmai = 10.0; run_test_sets(A, k, m, sigmar, sigmai); } TEST_CASE("Eigensolver of sparse real matrix [1000x1000]", "[eigs_gen]") { std::srand(123); const SpMatrix A = gen_sparse_data(1000, 0.01); int k = 20; int m = 50; double sigmar = 200.0; double sigmai = 100.0; run_test_sets(A, k, m, sigmar, sigmai); }
4,876
C++
.cpp
157
26.420382
92
0.631613
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,746
JDSymEigsBase.cpp
openMVG_openMVG/src/third_party/spectra/test/JDSymEigsBase.cpp
#include <Eigen/Core> #include <Eigen/SparseCore> #include <iostream> #include <random> // Requires C++ 11 #include <Spectra/JDSymEigsBase.h> #include <Spectra/MatOp/DenseGenMatProd.h> using namespace Spectra; #include "catch.hpp" using Matrix = Eigen::MatrixXd; using Vector = Eigen::VectorXd; using ComplexMatrix = Eigen::MatrixXcd; using ComplexVector = Eigen::VectorXcd; using SpMatrix = Eigen::SparseMatrix<double>; using Index = Eigen::Index; template <typename OpType> class JDMock : public JDSymEigsBase<JDMock<OpType>, OpType> { public: JDMock(OpType& op, Index nev) : JDSymEigsBase<JDMock<OpType>, OpType>(op, nev) {} Matrix setup_initial_search_space(SortRule) const { return Matrix::Zero(0, 0); } Matrix calculate_correction_vector() const { return Matrix::Zero(0, 0); } }; TEST_CASE("Constructing JDSymObject", "[eigs_gen]") { const Matrix A = Eigen::MatrixXd::Random(10, 10); DenseGenMatProd<double> op(A); JDMock<DenseGenMatProd<double>> eigs(op, 5); REQUIRE(eigs.num_iterations() == 0); REQUIRE(eigs.info() == Spectra::CompInfo::NotComputed); }
1,139
C++
.cpp
37
27.702703
59
0.719234
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,749
Orthogonalization.cpp
openMVG_openMVG/src/third_party/spectra/test/Orthogonalization.cpp
#include <Eigen/Core> #include <Spectra/LinAlg/Orthogonalization.h> #include <iostream> using namespace Spectra; #include "catch.hpp" using Eigen::MatrixXd; using Eigen::VectorXd; using Eigen::Index; template <typename Matrix> void check_orthogonality(const Matrix& basis) { const double tol = 1e-12; Matrix xs = basis.transpose() * basis; INFO("The orthonormalized basis must fulfill that basis.T * basis = I"); INFO("Matrix is\n " << basis); INFO("Overlap is\n " << xs); CHECK(xs.isIdentity(tol)); } TEST_CASE("complete orthonormalization", "[orthogonalisation]") { std::srand(123); const Index n = 20; MatrixXd mat = MatrixXd::Random(n, n); SECTION("MGS") { MGS_orthogonalisation(mat); check_orthogonality(mat); } SECTION("GS") { GS_orthogonalisation(mat); check_orthogonality(mat); } SECTION("QR") { QR_orthogonalisation(mat); check_orthogonality(mat); } SECTION("twice_is_enough") { twice_is_enough_orthogonalisation(mat); check_orthogonality(mat); } SECTION("JensWehner") { JensWehner_orthogonalisation(mat); check_orthogonality(mat); } } TEST_CASE("Partial orthonormalization", "[orthogonalisation]") { std::srand(123); const Index n = 20; const Index sub = 5; Index start = n - sub; // Create a n x 20 orthonormal basis MatrixXd mat = MatrixXd::Random(n, start); QR_orthogonalisation(mat); mat.conservativeResize(Eigen::NoChange, n); mat.rightCols(sub) = MatrixXd::Random(n, sub); SECTION("MGS") { MGS_orthogonalisation(mat, start); check_orthogonality(mat); } SECTION("GS") { GS_orthogonalisation(mat, start); check_orthogonality(mat); } SECTION("twice_is_enough") { twice_is_enough_orthogonalisation(mat, start); check_orthogonality(mat); } SECTION("JensWehner") { JensWehner_orthogonalisation(mat, start); check_orthogonality(mat); } }
2,087
C++
.cpp
81
20.567901
76
0.647739
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,750
RitzPairs.cpp
openMVG_openMVG/src/third_party/spectra/test/RitzPairs.cpp
#include <Eigen/Core> #include <Eigen/SparseCore> #include <iostream> #include <Spectra/MatOp/DenseGenMatProd.h> #include <Spectra/Util/SelectionRule.h> #include <Spectra/LinAlg/SearchSpace.h> #include <Spectra/LinAlg/RitzPairs.h> #include <Spectra/LinAlg/Orthogonalization.h> using namespace Spectra; #include "catch.hpp" using Matrix = Eigen::MatrixXd; using Vector = Eigen::VectorXd; using ComplexMatrix = Eigen::MatrixXcd; using ComplexVector = Eigen::VectorXcd; using SpMatrix = Eigen::SparseMatrix<double>; using Index = Eigen::Index; TEST_CASE("compute_eigen_pairs", "[RitzPairs]") { Matrix A = Eigen::MatrixXd::Random(10, 10); Matrix B = A + A.transpose(); DenseGenMatProd<double> op(B); SearchSpace<double> space; Matrix initial_space = Matrix::Random(10, 3); Spectra::twice_is_enough_orthogonalisation(initial_space); space.initialize_search_space(initial_space); space.update_operator_basis_product(op); RitzPairs<double> ritzpair; ritzpair.compute_eigen_pairs(space); SECTION("Largest Magnitude") { } } TEST_CASE("Convergence", "[RitzPairs]") { Matrix A = Eigen::MatrixXd::Random(10, 10); Matrix B = A + A.transpose(); DenseGenMatProd<double> op(B); }
1,236
C++
.cpp
38
29.631579
62
0.740336
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,751
SparseSymMatProd.cpp
openMVG_openMVG/src/third_party/spectra/test/SparseSymMatProd.cpp
#include <Spectra/MatOp/SparseSymMatProd.h> #include <Eigen/Core> #include <Eigen/SparseCore> using namespace Spectra; #include "catch.hpp" using Eigen::Index; template <typename TestType> using Matrix = Eigen::Matrix<TestType, Eigen::Dynamic, Eigen::Dynamic>; template <typename T> Eigen::SparseMatrix<T> generate_random_sparse(Index rows, Index cols) { std::default_random_engine gen; std::uniform_real_distribution<T> dist(0.0, 1.0); std::vector<Eigen::Triplet<T>> tripletVector; for (int i = 0; i < rows; ++i) for (int j = 0; j < cols; ++j) { auto v_ij = dist(gen); if (v_ij < 0.5) { // if larger than treshold, insert it tripletVector.push_back(Eigen::Triplet<T>(i, j, v_ij)); } } Eigen::SparseMatrix<T> mat(rows, cols); // create the matrix mat.setFromTriplets(tripletVector.begin(), tripletVector.end()); return mat; } TEMPLATE_TEST_CASE("matrix operations", "[SparseSymMatProd]", float, double) { std::srand(123); constexpr Index n = 100; Eigen::SparseMatrix<TestType> mat = generate_random_sparse<TestType>(n, n); Eigen::SparseMatrix<TestType> mat1 = mat + Eigen::SparseMatrix<TestType>(mat.transpose()); // It needs to be symetric Matrix<TestType> mat2 = Matrix<TestType>::Random(n, n); SparseSymMatProd<TestType> sparse1(mat1); Matrix<TestType> xs = sparse1 * mat2; Matrix<TestType> ys = mat1 * mat2; INFO("The matrix-matrix product must be the same as in eigen.") REQUIRE(xs.isApprox(ys)); INFO("The accesor operator must produce the same element as in eigen") REQUIRE(mat1.coeff(45, 22) == sparse1(45, 22)); }
1,719
C++
.cpp
44
33.636364
122
0.664663
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,752
SymGEigsRegInv.cpp
openMVG_openMVG/src/third_party/spectra/test/SymGEigsRegInv.cpp
#include <Eigen/Core> #include <Eigen/SparseCore> #include <iostream> #include <random> // Requires C++ 11 #include <Spectra/SymGEigsSolver.h> #include <Spectra/MatOp/SparseSymMatProd.h> #include <Spectra/MatOp/SparseRegularInverse.h> using namespace Spectra; #include "catch.hpp" using Matrix = Eigen::MatrixXd; using Vector = Eigen::VectorXd; using SpMatrix = Eigen::SparseMatrix<double>; // Generate random sparse matrix SpMatrix sprand(int size, double prob = 0.5) { SpMatrix mat(size, size); std::default_random_engine gen; gen.seed(0); std::uniform_real_distribution<double> distr(0.0, 1.0); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (distr(gen) < prob) mat.insert(i, j) = distr(gen) - 0.5; } } return mat; } void gen_sparse_data(int n, SpMatrix& A, SpMatrix& B, double prob = 0.1) { // Eigen solver only uses the lower triangle of A, // so we don't need to make A symmetric here. A = sprand(n, prob); B = A.transpose() * A; // To make sure B is positive definite for (int i = 0; i < n; i++) B.coeffRef(i, i) += 0.1; } template <typename Solver> void run_test(const SpMatrix& A, const SpMatrix& B, Solver& eigs, SortRule selection, bool allow_fail = false) { eigs.init(); // maxit = 100 to reduce running time for failed cases int nconv = eigs.compute(selection, 100); int niter = eigs.num_iterations(); int nops = eigs.num_operations(); if (allow_fail && eigs.info() != CompInfo::Successful) { WARN("FAILED on this test"); std::cout << "nconv = " << nconv << std::endl; std::cout << "niter = " << niter << std::endl; std::cout << "nops = " << nops << std::endl; return; } else { INFO("nconv = " << nconv); INFO("niter = " << niter); INFO("nops = " << nops); REQUIRE(eigs.info() == CompInfo::Successful); } Vector evals = eigs.eigenvalues(); Matrix evecs = eigs.eigenvectors(); Matrix resid = A.template selfadjointView<Eigen::Lower>() * evecs - B.template selfadjointView<Eigen::Lower>() * evecs * evals.asDiagonal(); const double err = resid.array().abs().maxCoeff(); INFO("||AU - BUD||_inf = " << err); REQUIRE(err == Approx(0.0).margin(1e-9)); } void run_test_sets(const SpMatrix& A, const SpMatrix& B, int k, int m) { using OpType = SparseSymMatProd<double>; using BOpType = SparseRegularInverse<double>; OpType op(A); BOpType Bop(B); SymGEigsSolver<OpType, BOpType, GEigsMode::RegularInverse> eigs(op, Bop, k, m); SECTION("Largest Magnitude") { run_test(A, B, eigs, SortRule::LargestMagn); } SECTION("Largest Value") { run_test(A, B, eigs, SortRule::LargestAlge); } SECTION("Smallest Magnitude") { run_test(A, B, eigs, SortRule::SmallestMagn, true); } SECTION("Smallest Value") { run_test(A, B, eigs, SortRule::SmallestAlge); } SECTION("Both Ends") { run_test(A, B, eigs, SortRule::BothEnds); } } TEST_CASE("Generalized eigensolver of sparse symmetric real matrix [10x10]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix A, B; gen_sparse_data(10, A, B, 0.5); int k = 3; int m = 6; run_test_sets(A, B, k, m); } TEST_CASE("Generalized eigensolver of sparse symmetric real matrix [100x100]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix A, B; gen_sparse_data(100, A, B, 0.1); int k = 10; int m = 20; run_test_sets(A, B, k, m); } TEST_CASE("Generalized eigensolver of sparse symmetric real matrix [1000x1000]", "[geigs_sym]") { std::srand(123); // Eigen solver only uses the lower triangle SpMatrix A, B; gen_sparse_data(1000, A, B, 0.01); int k = 20; int m = 50; run_test_sets(A, B, k, m); }
4,005
C++
.cpp
128
26.460938
110
0.621012
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,754
Eigen.cpp
openMVG_openMVG/src/third_party/spectra/test/Eigen.cpp
// Test ../include/Spectra/LinAlg/UpperHessenbergEigen.h and // ../include/Spectra/LinAlg/TridiagEigen.h #include <ctime> #include <iostream> #include <Eigen/Core> #include <Eigen/Eigenvalues> #include <Spectra/LinAlg/UpperHessenbergEigen.h> #include <Spectra/LinAlg/TridiagEigen.h> using namespace Spectra; #include "catch.hpp" using Matrix = Eigen::MatrixXd; using Vector = Eigen::VectorXd; using ComplexMatrix = Eigen::MatrixXcd; using ComplexVector = Eigen::VectorXcd; TEST_CASE("Eigen decomposition of upper Hessenberg matrix", "[Eigen]") { std::srand(123); const int n = 100; Matrix M = Matrix::Random(n, n); M.array() -= 0.5; // H is upper Hessenberg Matrix H = M.triangularView<Eigen::Upper>(); H.diagonal(-1) = M.diagonal(-1); UpperHessenbergEigen<double> decomp(H); ComplexVector evals = decomp.eigenvalues(); ComplexMatrix evecs = decomp.eigenvectors(); // Test accuracy ComplexMatrix err = H * evecs - evecs * evals.asDiagonal(); INFO("||HU - UD||_inf = " << err.cwiseAbs().maxCoeff()); REQUIRE(err.cwiseAbs().maxCoeff() == Approx(0.0).margin(1e-12)); clock_t t1, t2; t1 = clock(); for (int i = 0; i < 100; i++) { UpperHessenbergEigen<double> decomp(H); ComplexVector evals = decomp.eigenvalues(); ComplexMatrix evecs = decomp.eigenvectors(); } t2 = clock(); std::cout << "elapsed time for UpperHessenbergEigen: " << double(t2 - t1) / CLOCKS_PER_SEC << " secs\n"; t1 = clock(); for (int i = 0; i < 100; i++) { Eigen::EigenSolver<Matrix> decomp(H); ComplexVector evals = decomp.eigenvalues(); ComplexMatrix evecs = decomp.eigenvectors(); } t2 = clock(); std::cout << "elapsed time for Eigen::EigenSolver: " << double(t2 - t1) / CLOCKS_PER_SEC << " secs\n"; } TEST_CASE("Eigen decomposition of symmetric tridiagonal matrix", "[Eigen]") { std::srand(123); const int n = 100; Matrix M = Matrix::Random(n, n); M.array() -= 0.5; // H is symmetric tridiagonal Matrix H = Matrix::Zero(n, n); H.diagonal() = M.diagonal(); H.diagonal(-1) = M.diagonal(-1); H.diagonal(1) = M.diagonal(-1); TridiagEigen<double> decomp(H); Vector evals = decomp.eigenvalues(); Matrix evecs = decomp.eigenvectors(); // Test accuracy Matrix err = H * evecs - evecs * evals.asDiagonal(); INFO("||HU - UD||_inf = " << err.cwiseAbs().maxCoeff()); REQUIRE(err.cwiseAbs().maxCoeff() == Approx(0.0).margin(1e-12)); clock_t t1, t2; t1 = clock(); for (int i = 0; i < 100; i++) { TridiagEigen<double> decomp(H); Vector evals = decomp.eigenvalues(); Matrix evecs = decomp.eigenvectors(); } t2 = clock(); std::cout << "elapsed time for TridiagEigen: " << double(t2 - t1) / CLOCKS_PER_SEC << " secs\n"; t1 = clock(); for (int i = 0; i < 100; i++) { Eigen::SelfAdjointEigenSolver<Matrix> decomp(H); Vector evals = decomp.eigenvalues(); Matrix evecs = decomp.eigenvectors(); } t2 = clock(); std::cout << "elapsed time for Eigen::SelfAdjointEigenSolver: " << double(t2 - t1) / CLOCKS_PER_SEC << " secs\n"; }
3,267
C++
.cpp
92
30.282609
75
0.622707
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,755
DenseSymMatProd.cpp
openMVG_openMVG/src/third_party/spectra/test/DenseSymMatProd.cpp
#include <Spectra/MatOp/DenseSymMatProd.h> #include <Eigen/Dense> #include <Eigen/Core> using namespace Spectra; #include "catch.hpp" #include <complex> template <typename TestType> using Matrix = Eigen::Matrix<TestType, Eigen::Dynamic, Eigen::Dynamic>; using Eigen::Index; TEMPLATE_TEST_CASE("matrix operations", "[DenseSymMatProd]", float, double) { std::srand(123); constexpr Index n = 100; Matrix<TestType> mat = Matrix<TestType>::Random(n, n); Matrix<TestType> mat1 = mat + mat.transpose(); // It needs to be symetric Matrix<TestType> mat2 = Matrix<TestType>::Random(n, n); DenseSymMatProd<TestType> dense1(mat1); Matrix<TestType> xs = dense1 * mat2; Matrix<TestType> ys = mat1 * mat2; INFO("The matrix-matrix product must be the same as in eigen.") REQUIRE(xs.isApprox(ys)); INFO("The accesor operator must produce the same element as in eigen") REQUIRE(mat1(15, 23) == dense1(23, 15)); }
952
C++
.cpp
24
36.333333
78
0.717391
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,756
JDSymEigsDPRConstructor.cpp
openMVG_openMVG/src/third_party/spectra/test/JDSymEigsDPRConstructor.cpp
#include <Eigen/Core> #include <Eigen/SparseCore> #include <Spectra/DavidsonSymEigsSolver.h> #include <Spectra/MatOp/DenseGenMatProd.h> using namespace Spectra; #include "catch.hpp" TEMPLATE_TEST_CASE("Constructing JDSymEigsDPR", "[JDSymEigsDPR]", float, double) { using Matrix = Eigen::Matrix<TestType, Eigen::Dynamic, Eigen::Dynamic>; const Matrix A = Matrix::Random(10, 10); DenseGenMatProd<TestType> op(A); DavidsonSymEigsSolver<DenseGenMatProd<TestType>> eigs{op, 5}; REQUIRE(eigs.num_iterations() == 0); REQUIRE(eigs.info() == Spectra::CompInfo::NotComputed); }
595
C++
.cpp
15
36.866667
80
0.750433
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,757
GenEigs.cpp
openMVG_openMVG/src/third_party/spectra/test/GenEigs.cpp
#include <Eigen/Core> #include <Eigen/SparseCore> #include <iostream> #include <type_traits> #include <random> // Requires C++ 11 #include <Spectra/GenEigsSolver.h> #include <Spectra/MatOp/DenseGenMatProd.h> #include <Spectra/MatOp/SparseGenMatProd.h> using namespace Spectra; #include "catch.hpp" using Matrix = Eigen::MatrixXd; using Vector = Eigen::VectorXd; using ComplexMatrix = Eigen::MatrixXcd; using ComplexVector = Eigen::VectorXcd; using SpMatrix = Eigen::SparseMatrix<double>; // Generate random sparse matrix SpMatrix gen_sparse_data(int n, double prob = 0.5) { SpMatrix mat(n, n); std::default_random_engine gen; gen.seed(0); std::uniform_real_distribution<double> distr(0.0, 1.0); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (distr(gen) < prob) mat.insert(i, j) = distr(gen) - 0.5; } } return mat; } template <typename MatType, typename Solver> void run_test(const MatType& mat, Solver& eigs, SortRule selection, bool allow_fail = false) { eigs.init(); // maxit = 300 to reduce running time for failed cases int nconv = eigs.compute(selection, 300); int niter = eigs.num_iterations(); int nops = eigs.num_operations(); if (allow_fail && eigs.info() != CompInfo::Successful) { WARN("FAILED on this test"); std::cout << "nconv = " << nconv << std::endl; std::cout << "niter = " << niter << std::endl; std::cout << "nops = " << nops << std::endl; return; } else { INFO("nconv = " << nconv); INFO("niter = " << niter); INFO("nops = " << nops); REQUIRE(eigs.info() == CompInfo::Successful); } ComplexVector evals = eigs.eigenvalues(); ComplexMatrix evecs = eigs.eigenvectors(); ComplexMatrix resid = mat * evecs - evecs * evals.asDiagonal(); const double err = resid.array().abs().maxCoeff(); INFO("||AU - UD||_inf = " << err); REQUIRE(err == Approx(0.0).margin(1e-9)); } template <typename MatType> void run_test_sets(const MatType& A, int k, int m) { constexpr bool is_dense = std::is_same<MatType, Matrix>::value; using DenseOp = DenseGenMatProd<double>; using SparseOp = SparseGenMatProd<double>; using OpType = typename std::conditional<is_dense, DenseOp, SparseOp>::type; OpType op(A); GenEigsSolver<OpType> eigs(op, k, m); SECTION("Largest Magnitude") { run_test(A, eigs, SortRule::LargestMagn); } SECTION("Largest Real Part") { run_test(A, eigs, SortRule::LargestReal); } SECTION("Largest Imaginary Part") { run_test(A, eigs, SortRule::LargestImag); } SECTION("Smallest Magnitude") { run_test(A, eigs, SortRule::SmallestMagn, true); } SECTION("Smallest Real Part") { run_test(A, eigs, SortRule::SmallestReal); } SECTION("Smallest Imaginary Part") { run_test(A, eigs, SortRule::SmallestImag, true); } } TEST_CASE("Eigensolver of general real matrix [10x10]", "[eigs_gen]") { std::srand(123); const Matrix A = Matrix::Random(10, 10); int k = 3; int m = 6; run_test_sets(A, k, m); } TEST_CASE("Eigensolver of general real matrix [100x100]", "[eigs_gen]") { std::srand(123); const Matrix A = Matrix::Random(100, 100); int k = 10; int m = 30; run_test_sets(A, k, m); } TEST_CASE("Eigensolver of general real matrix [1000x1000]", "[eigs_gen]") { std::srand(123); const Matrix A = Matrix::Random(1000, 1000); int k = 20; int m = 50; run_test_sets(A, k, m); } TEST_CASE("Eigensolver of sparse real matrix [10x10]", "[eigs_gen]") { std::srand(123); const SpMatrix A = gen_sparse_data(10, 0.5); int k = 3; int m = 6; run_test_sets(A, k, m); } TEST_CASE("Eigensolver of sparse real matrix [100x100]", "[eigs_gen]") { std::srand(123); const SpMatrix A = gen_sparse_data(100, 0.1); int k = 10; int m = 30; run_test_sets(A, k, m); } TEST_CASE("Eigensolver of sparse real matrix [1000x1000]", "[eigs_gen]") { std::srand(123); const SpMatrix A = gen_sparse_data(1000, 0.01); int k = 20; int m = 50; run_test_sets(A, k, m); }
4,267
C++
.cpp
144
25.027778
92
0.624633
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,760
SearchSpace.cpp
openMVG_openMVG/src/third_party/spectra/test/SearchSpace.cpp
#include <Eigen/Core> #include <Eigen/SparseCore> #include <iostream> #include <Spectra/MatOp/DenseGenMatProd.h> #include <Spectra/LinAlg/SearchSpace.h> #include <Spectra/LinAlg/Orthogonalization.h> using namespace Spectra; #include "catch.hpp" using Matrix = Eigen::MatrixXd; using Vector = Eigen::VectorXd; using ComplexMatrix = Eigen::MatrixXcd; using ComplexVector = Eigen::VectorXcd; using SpMatrix = Eigen::SparseMatrix<double>; using Index = Eigen::Index; TEST_CASE("CompleteSearchSpace", "[SearchSpace]") { SearchSpace<double> space; Matrix initial_space = Matrix::Random(10, 3); Spectra::twice_is_enough_orthogonalisation(initial_space); space.initialize_search_space(initial_space); REQUIRE(space.basis_vectors().cols() == 3); REQUIRE(space.operator_basis_product().cols() == 0); Matrix A = Eigen::MatrixXd::Random(10, 10); Matrix B = A + A.transpose(); DenseGenMatProd<double> op(B); space.update_operator_basis_product(op); REQUIRE(space.basis_vectors().cols() == 3); REQUIRE(space.operator_basis_product().cols() == 3); REQUIRE(space.operator_basis_product().isApprox(B * initial_space)); Matrix append_space = Matrix::Random(10, 3); space.extend_basis(append_space); REQUIRE((space.basis_vectors().transpose() * space.basis_vectors()).isIdentity(1e-12)); REQUIRE(space.basis_vectors().cols() == 6); REQUIRE(space.operator_basis_product().cols() == 3); space.update_operator_basis_product(op); REQUIRE(space.operator_basis_product().cols() == 6); RitzPairs<double> ritzpair; ritzpair.compute_eigen_pairs(space); REQUIRE(ritzpair.size() == 6); space.restart(ritzpair, 2); REQUIRE(space.basis_vectors().cols() == 2); REQUIRE(space.operator_basis_product().cols() == 2); }
1,796
C++
.cpp
43
38.139535
91
0.717317
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,761
DavidsonSymEigs_example.cpp
openMVG_openMVG/src/third_party/spectra/examples/DavidsonSymEigs_example.cpp
#include <Eigen/Dense> #include <Spectra/DavidsonSymEigsSolver.h> #include <Spectra/MatOp/DenseSymMatProd.h> #include <iostream> using namespace Spectra; int main() { Eigen::Index n = 1000; Eigen::MatrixXd mat = 0.03 * Eigen::MatrixXd::Random(n, n); Eigen::MatrixXd mat1 = mat + mat.transpose(); for (Eigen::Index i = 0; i < n; i++) { mat1(i, i) += i + 1; } DenseSymMatProd<double> op_dense(mat1); // Create the Matrix Product operation Eigen::Index num_of_eigenvalues = 5; DavidsonSymEigsSolver<DenseSymMatProd<double>> solver(op_dense, num_of_eigenvalues); // Create Solver Eigen::Index iterations = 100; double tolerance = 1e-3; int nconv = solver.compute(SortRule::LargestAlge, iterations, tolerance); // Retrieve results Eigen::VectorXd evalues; if (solver.info() == CompInfo::Successful) { evalues = solver.eigenvalues(); std::cout << nconv << " Eigenvalues found:\n" << evalues << std::endl; } else { std::cout << "Calculation failed" << std::endl; } return 0; }
1,112
C++
.cpp
34
27.588235
106
0.64459
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,778
registration_to_exif_gps_position.cpp
openMVG_openMVG/src/software/Geodesy/registration_to_exif_gps_position.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2016 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/geometry/rigid_transformation3D_srt.hpp" #include "openMVG/geometry/Similarity3.hpp" #include "openMVG/geometry/Similarity3_Kernel.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/sfm/sfm_data_transform.hpp" #include "openMVG/exif/exif_IO_EasyExif.hpp" #include "openMVG/geodesy/geodesy.hpp" // //- Robust estimation - LMeds (since no threshold can be defined) #include "openMVG/robust_estimation/robust_estimator_LMeds.hpp" #include "software/SfM/SfMPlyHelper.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include "third_party/cmdLine/cmdLine.h" #include <iostream> #include <iomanip> #include <string> using namespace openMVG; using namespace openMVG::exif; using namespace openMVG::geodesy; using namespace openMVG::sfm; int main(int argc, char **argv) { enum ERegistrationType { ROBUST_RIGID_REGISTRATION = 0, RIGID_REGISTRATION_ALL_POINTS = 1 }; std::string sSfM_Data_Filename_In, sSfM_Data_Filename_Out; unsigned int rigid_registration_method = ERegistrationType::RIGID_REGISTRATION_ALL_POINTS; int i_GPS_XYZ_method = 0; CmdLine cmd; cmd.add(make_option('i', sSfM_Data_Filename_In, "input_file")); cmd.add(make_option('o', sSfM_Data_Filename_Out, "output_file")); cmd.add(make_option('m', rigid_registration_method, "method")); cmd.add(make_option('M', i_GPS_XYZ_method, "gps_to_xyz_method")); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << " GPS registration of a SfM Data scene,\n" << "[-i|--input_file] path to the input SfM_Data scene\n" << "[-o|--output_file] path to the output SfM_Data scene\n" << "[-m|--method] method to use for the rigid registration\n" << "\t0 => registration is done using a robust estimation,\n" << "\t1 (default)=> registration is done using all points.\n" << "[-M|--gps_to_xyz_method] XZY Coordinate system:\n" << "\t 0: ECEF (default)\n" << "\t 1: UTM" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } if (sSfM_Data_Filename_In.empty() || sSfM_Data_Filename_Out.empty()) { std::cerr << "Invalid input or output filename." << std::endl; return EXIT_FAILURE; } // // Load a SfM scene // For each valid view (pose & intrinsic defined) // - iff a GPS position can be parsed // - store corresponding camera pose & GPS position // - Compute the registration between the selected camera poses & GPS positions // Load input SfM_Data scene SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename_In, ESfM_Data(ALL))) { std::cerr << "\nThe input SfM_Data file \"" << sSfM_Data_Filename_In << "\" cannot be read." << std::endl; return EXIT_FAILURE; } // Init the EXIF reader (will be used for GPS data reading) Exif_IO_EasyExif exifReader; // List corresponding poses (SfM - GPS) std::vector<Vec3> vec_sfm_center, vec_gps_center; for (const auto & view_it : sfm_data.GetViews() ) { if (!sfm_data.IsPoseAndIntrinsicDefined(view_it.second.get())) continue; const std::string view_filename = stlplus::create_filespec(sfm_data.s_root_path, view_it.second->s_Img_path); // Try to parse EXIF metada & check existence of EXIF data if (! (exifReader.open( view_filename ) && exifReader.doesHaveExifInfo()) ) continue; // Check existence of GPS coordinates double latitude, longitude, altitude; if ( exifReader.GPSLatitude( &latitude ) && exifReader.GPSLongitude( &longitude ) && exifReader.GPSAltitude( &altitude ) ) { // Add XYZ position to the GPS position array switch (i_GPS_XYZ_method) { case 1: vec_gps_center.push_back(lla_to_utm(latitude, longitude, altitude)); break; case 0: default: vec_gps_center.push_back(lla_to_ecef(latitude, longitude, altitude)); break; } const openMVG::geometry::Pose3 pose(sfm_data.GetPoseOrDie(view_it.second.get())); vec_sfm_center.push_back( pose.center() ); } } if ( vec_sfm_center.empty() ) { std::cerr << "No valid corresponding GPS data found for the used views." << std::endl; return EXIT_FAILURE; } std::cout << std::endl << "Registration report:\n" << " #corresponding SFM - GPS data: " << vec_sfm_center.size() << "\n" << std::endl; // Export the corresponding poses (for debugging & see the transformation) plyHelper::exportToPly( vec_gps_center, stlplus::create_filespec(stlplus::folder_part(sSfM_Data_Filename_Out), "GPS_position", "ply")); plyHelper::exportToPly( vec_sfm_center, stlplus::create_filespec(stlplus::folder_part(sSfM_Data_Filename_Out), "SFM_position", "ply")); { // Convert positions to the appropriate data container const Mat X_SfM = Eigen::Map<Mat>(vec_sfm_center[0].data(), 3, vec_sfm_center.size()); const Mat X_GPS = Eigen::Map<Mat>(vec_gps_center[0].data(), 3, vec_gps_center.size()); openMVG::geometry::Similarity3 sim; // Compute the registration: // - using a rigid scheme (using all points) // - using a robust scheme (using partial points - robust estimation) switch (rigid_registration_method) { case ERegistrationType::ROBUST_RIGID_REGISTRATION: { using namespace openMVG::robust; using namespace openMVG::geometry; geometry::kernel::Similarity3_Kernel kernel(X_SfM, X_GPS); const double lmeds_median = LeastMedianOfSquares ( kernel, &sim ); std::cout << "LMeds found a model with an upper bound of: " << sqrt(lmeds_median) << " user units."<< std::endl; // Compute & display fitting errors { const Vec vec_fitting_errors_eigen( geometry::kernel::Similarity3ErrorSquaredMetric::ErrorVec(sim, X_SfM, X_GPS).array().sqrt()); std::cout << "\n3D Similarity fitting error using all points (in target coordinate system units):"; minMaxMeanMedian<float>( vec_fitting_errors_eigen.data(), vec_fitting_errors_eigen.data() + vec_fitting_errors_eigen.rows(), std::cout); } // INLIERS only { std::vector<float> vec_fitting_errors; for (Mat::Index i = 0; i < X_SfM.cols(); ++i) { if (geometry::kernel::Similarity3ErrorSquaredMetric::Error(sim, X_SfM.col(i), X_GPS.col(i)) < lmeds_median) vec_fitting_errors.push_back((X_GPS.col(i) - sim(X_SfM.col(i))).norm()); } std::cout << "\nFound: " << vec_fitting_errors.size() << " inliers" << " from " << X_SfM.cols() << " points." << std::endl; std::cout << "\n3D Similarity fitting error using only the fitted inliers (in target coordinate system units):"; minMaxMeanMedian<float>( vec_fitting_errors.cbegin(), vec_fitting_errors.cend(), std::cout); } } break; case ERegistrationType::RIGID_REGISTRATION_ALL_POINTS: { Vec3 t; Mat3 R; double S; if (!openMVG::geometry::FindRTS(X_SfM, X_GPS, &S, &t, &R)) { std::cerr << "Failed to compute the registration" << std::endl; return EXIT_FAILURE; } std::cout << "Found transform:\n" << " scale: " << S << "\n" << " rotation:\n" << R << "\n" << " translation: " << std::fixed << std::setprecision(9) << t.transpose() << std::endl; // Encode the transformation as a 3D Similarity transformation matrix // S * R * X + t sim = openMVG::geometry::Similarity3(geometry::Pose3(R, -R.transpose()* t/S), S); // Compute & display fitting errors { const Vec vec_fitting_errors_eigen( geometry::kernel::Similarity3ErrorSquaredMetric::ErrorVec(sim, X_SfM, X_GPS).array().sqrt()); std::cout << "\n3D Similarity fitting error (in target coordinate system units):"; minMaxMeanMedian<float>( vec_fitting_errors_eigen.data(), vec_fitting_errors_eigen.data() + vec_fitting_errors_eigen.rows(), std::cout); } } break; default: std::cerr << "Unknow rigid registration method" << std::endl; return EXIT_FAILURE; } //-- // Apply the found transformation to the SfM Data Scene //-- openMVG::sfm::ApplySimilarity(sim, sfm_data); } // Export the SfM_Data scene in the expected format if (Save( sfm_data, sSfM_Data_Filename_Out.c_str(), ESfM_Data(ALL))) { return EXIT_SUCCESS; } else { std::cerr << std::endl << "An error occured while trying to save \"" << sSfM_Data_Filename_Out << "\"." << std::endl; return EXIT_FAILURE; } return EXIT_FAILURE; }
9,348
C++
.cpp
235
33.73617
122
0.639027
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,779
main_SfM_Localization.cpp
openMVG_openMVG/src/software/Localization/main_SfM_Localization.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // The <cereal/archives> headers are special and must be included first. #include <cereal/archives/json.hpp> #include <openMVG/features/feature.hpp> #include <openMVG/features/image_describer.hpp> #include <openMVG/image/image_io.hpp> #include <openMVG/sfm/sfm.hpp> #include <openMVG/system/loggerprogress.hpp> #include <openMVG/system/timer.hpp> #include <openMVG/stl/stl.hpp> #include <software/SfM/SfMPlyHelper.hpp> using namespace openMVG; using namespace openMVG::sfm; #include "nonFree/sift/SIFT_describer_io.hpp" #include "openMVG/features/akaze/image_describer_akaze_io.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cstdlib> #ifdef OPENMVG_USE_OPENMP #include <omp.h> #endif // Naive function for finding the biggest common root dir from two paths std::string FindCommonRootDir(const std::string & dir1, const std::string & dir2) { int i = 0; for (; i != std::min(dir1.size(), dir2.size()); i++) { if (dir1[i] != dir2[i]) break; } return dir1.substr(0,i); } // ---------------------------------------------------- // Multiple Images localization from an existing reconstruction // ---------------------------------------------------- int main(int argc, char **argv) { std::cout << std::endl << "-----------------------------------------------------------\n" << " Images localization in an existing SfM reconstruction:\n" << "-----------------------------------------------------------\n" << std::endl; CmdLine cmd; std::string sSfM_Data_Filename; std::string sMatchesDir; std::string sOutDir = ""; std::string sMatchesOutDir; std::string sQueryDir; double dMaxResidualError = std::numeric_limits<double>::infinity(); int i_User_camera_model = cameras::PINHOLE_CAMERA_RADIAL3; bool bUseSingleIntrinsics = false; bool bExportStructure = false; int resection_method = static_cast<int>(resection::SolverType::DEFAULT); #ifdef OPENMVG_USE_OPENMP int iNumThreads = 0; #endif cmd.add( make_option('i', sSfM_Data_Filename, "input_file") ); cmd.add( make_option('m', sMatchesDir, "match_dir") ); cmd.add( make_option('o', sOutDir, "out_dir") ); cmd.add( make_option('u', sMatchesOutDir, "match_out_dir") ); cmd.add( make_option('q', sQueryDir, "query_image_dir")); cmd.add( make_option('r', dMaxResidualError, "residual_error")); cmd.add( make_option('c', i_User_camera_model, "camera_model") ); cmd.add( make_switch('s', "single_intrinsics")); cmd.add( make_switch('e', "export_structure")); cmd.add( make_option('R', resection_method, "resection_method")); #ifdef OPENMVG_USE_OPENMP cmd.add( make_option('n', iNumThreads, "numThreads") ); #endif try { if (argc == 1) throw std::string("Invalid parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_file] path to a SfM_Data scene\n" << "[-m|--match_dir] path to the directory containing the matches\n" << " corresponding to the provided SfM_Data scene\n" << "[-o|--out_dir] path where the output data will be stored\n" << "[-u|--match_out_dir] path to the directory where new matches will be stored\n" << " (if empty the initial matching directory will be used)\n" << "[-q|--query_image_dir] path to an image OR to the directory containing the images that must be localized\n" << " (the directory can also contain the images from the initial reconstruction)\n" << "\n" << "(optional)\n" << "[-r|--residual_error] upper bound of the residual error tolerance\n" << "[-s|--single_intrinsics] (switch) when switched on, the program will check if the input sfm_data\n" << " contains a single intrinsics and, if so, take this value as intrinsics for the query images.\n" << " (OFF by default)\n" << "[-e|--export_structure] (switch) when switched on, the program will also export structure to output sfm_data.\n" << " if OFF only VIEWS, INTRINSICS and EXTRINSICS are exported (OFF by default)\n" << "[-c|--camera_model] Camera model type for view with unknown intrinsic:\n" << "\t 1: Pinhole\n" << "\t 2: Pinhole radial 1\n" << "\t 3: Pinhole radial 3 (default)\n" << "\t 4: Pinhole radial 3 + tangential 2\n" << "\t 5: Pinhole fisheye\n" << "\t 7: Spherical camera\n" << "[-R|--resection_method] resection/pose estimation method (default=" << resection_method << "):\n" << "\t" << static_cast<int>(resection::SolverType::DLT_6POINTS) << ": DIRECT_LINEAR_TRANSFORM 6Points | does not use intrinsic data\n" << "\t" << static_cast<int>(resection::SolverType::P3P_KE_CVPR17) << ": P3P_KE_CVPR17\n" << "\t" << static_cast<int>(resection::SolverType::P3P_KNEIP_CVPR11) << ": P3P_KNEIP_CVPR11\n" << "\t" << static_cast<int>(resection::SolverType::P3P_NORDBERG_ECCV18) << ": P3P_NORDBERG_ECCV18\n" << "\t" << static_cast<int>(resection::SolverType::P3P_DING_CVPR23) << ": P3P_DING_CVPR23\n" << "\t" << static_cast<int>(resection::SolverType::UP2P_KUKELOVA_ACCV10) << ": UP2P_KUKELOVA_ACCV10 | 2Points | upright camera\n" #ifdef OPENMVG_USE_OPENMP << "[-n|--numThreads] number of thread(s)\n" #endif << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } if ( !isValid(openMVG::cameras::EINTRINSIC(i_User_camera_model)) ) { std::cerr << "\n Invalid camera type" << std::endl; return EXIT_FAILURE; } // Load input SfM_Data scene SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(ALL))) { std::cerr << std::endl << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl; return EXIT_FAILURE; } if (sMatchesOutDir.empty()) { sMatchesOutDir = sMatchesDir; } if (sfm_data.GetPoses().empty() || sfm_data.GetLandmarks().empty()) { std::cerr << std::endl << "The input SfM_Data file have not 3D content to match with." << std::endl; return EXIT_FAILURE; } bUseSingleIntrinsics = cmd.used('s'); bExportStructure = cmd.used('e'); // --------------- // Initialization // --------------- // Init the regions_type from the image describer file (used for image regions extraction) using namespace openMVG::features; const std::string sImage_describer = stlplus::create_filespec(sMatchesDir, "image_describer", "json"); std::unique_ptr<Regions> regions_type = Init_region_type_from_file(sImage_describer); if (!regions_type) { std::cerr << "Invalid: " << sImage_describer << " regions type file." << std::endl; return EXIT_FAILURE; } // Init the feature extractor that have been used for the reconstruction std::unique_ptr<Image_describer> image_describer; if (stlplus::is_file(sImage_describer)) { // Dynamically load the image_describer from the file (will restore old used settings) std::ifstream stream(sImage_describer.c_str()); if (!stream) return EXIT_FAILURE; try { cereal::JSONInputArchive archive(stream); archive(cereal::make_nvp("image_describer", image_describer)); } catch (const cereal::Exception & e) { std::cerr << e.what() << std::endl << "Cannot dynamically allocate the Image_describer interface." << std::endl; return EXIT_FAILURE; } } else { std::cerr << "Expected file image_describer.json cannot be opened." << std::endl; return EXIT_FAILURE; } // Show the progress on the command line: system::LoggerProgress progress; // Load the SfM_Data region's views std::shared_ptr<Regions_Provider> regions_provider = std::make_shared<Regions_Provider>(); if (!regions_provider->load(sfm_data, sMatchesDir, regions_type, &progress)) { std::cerr << std::endl << "Invalid regions." << std::endl; return EXIT_FAILURE; } if ( !stlplus::folder_exists( sQueryDir ) && !stlplus::file_exists( sQueryDir ) ) { std::cerr << "\nThe query directory/file does not exist : " << std::endl; std::cerr << sQueryDir << std::endl; return EXIT_FAILURE; } if (sOutDir.empty()) { std::cerr << "\nPlease provide a valid directory for the option [-o|--out_dir]." << std::endl; return EXIT_FAILURE; } if (!stlplus::folder_exists(sOutDir)) stlplus::folder_create(sOutDir); if (bUseSingleIntrinsics && sfm_data.GetIntrinsics().size() != 1) { std::cout << "More than one intrinsics to compare to in input scene " << " => Consider intrinsics as unkown." << std::endl; } //-- Localization // - init the retrieval database // - Go along the sfm_data view // - extract the regions of the view // - try to locate the images // - add the images to the sfm_data scene std::vector<Vec3> vec_found_poses; sfm::SfM_Localization_Single_3DTrackObservation_Database localizer; if (!localizer.Init(sfm_data, *regions_provider.get())) { std::cerr << "Cannot initialize the SfM localizer" << std::endl; } // Since we have copied interesting data, release some memory regions_provider.reset(); // list images from sfm_data in a vector std::vector<std::string> vec_image_original (sfm_data.GetViews().size()); int n(-1); std::generate(vec_image_original.begin(), vec_image_original.end(), [&n,&sfm_data] { n++; return stlplus::filename_part(sfm_data.views.at(n)->s_Img_path); }); // list images in query directory std::vector<std::string> vec_image; if (stlplus::is_file(sQueryDir)) { vec_image.emplace_back(stlplus::filename_part(sQueryDir)); // single file sQueryDir = stlplus::folder_part(sQueryDir); } else vec_image = stlplus::folder_files(sQueryDir); // multiple files std::sort(vec_image.begin(), vec_image.end()); // find difference between two list of images std::vector<std::string> vec_image_new; std::set_difference(vec_image.cbegin(), vec_image.cend(), vec_image_original.cbegin(),vec_image_original.cend(), std::back_inserter(vec_image_new)); // find common root directory between images in vec_image_original and vec_images_new const std::string common_root_dir = FindCommonRootDir(sfm_data.s_root_path, sQueryDir); // check if sfm_data's root dir differs from the common root dir. if (sfm_data.s_root_path != common_root_dir) { // in that case we have to change all the image paths from the original // reconstruction for (auto & view : sfm_data.GetViews()) { view.second->s_Img_path = stlplus::create_filespec(stlplus::folder_to_relative_path(common_root_dir, sfm_data.s_root_path), view.second->s_Img_path); } // change root path to common root path sfm_data.s_root_path = common_root_dir; } // references Views & views = sfm_data.views; Poses & poses = sfm_data.poses; Intrinsics & intrinsics = sfm_data.intrinsics; int total_num_images = 0; #ifdef OPENMVG_USE_OPENMP const unsigned int nb_max_thread = (iNumThreads == 0) ? 0 : omp_get_max_threads(); omp_set_num_threads(nb_max_thread); #pragma omp parallel for schedule(dynamic) #endif for (int i = 0; i < static_cast<int>(vec_image_new.size()); ++i) { std::vector<std::string>::const_iterator iter_image = vec_image_new.begin(); std::advance(iter_image, i); // Test if the image format is supported: if (openMVG::image::GetFormat((*iter_image).c_str()) == openMVG::image::Unknown) { std::cerr << *iter_image << " : unknown image file format." << std::endl; continue; } std::cout << "SfM::localization => try with image: " << *iter_image << std::endl; std::unique_ptr<Regions> query_regions(regions_type->EmptyClone()); image::Image<unsigned char> imageGray; { const std::string sView_filename = stlplus::create_filespec(sQueryDir, *iter_image); // Try to open image if (!image::ReadImage(sView_filename.c_str(), &imageGray)) { std::cerr << "Cannot open the input provided image : " << *iter_image << std::endl; continue; } const std::string sFeat = stlplus::create_filespec(sMatchesOutDir, stlplus::basename_part(sView_filename.c_str()), "feat"), sDesc = stlplus::create_filespec(sMatchesOutDir, stlplus::basename_part(sView_filename.c_str()), "desc"); // Compute features and descriptors and save them if they don't exist yet if (!stlplus::file_exists(sFeat) || !stlplus::file_exists(sDesc)) { image_describer->Describe(imageGray, query_regions); image_describer->Save(query_regions.get(), sFeat, sDesc); std::cout << "#regions detected in query image: " << query_regions->RegionCount() << std::endl; } else // load already existing regions { query_regions->Load(sFeat,sDesc); } } std::shared_ptr<cameras::IntrinsicBase> optional_intrinsic; if (bUseSingleIntrinsics) { if (sfm_data.GetIntrinsics().size() != 1) { std::cerr << "You choose the single intrinsic mode but the sfm_data scene," <<" have too few or too much intrinsics." << std::endl; continue; } optional_intrinsic = sfm_data.GetIntrinsics().at(0); if (imageGray.Width() != optional_intrinsic->w() || optional_intrinsic->h() != imageGray.Height()) { std::cout << "The provided image does not have the same size as the camera model you want to use." << std::endl; continue; } } if (optional_intrinsic) { std::cout << "- use known intrinsics." << std::endl; } else { std::cout << "- use Unknown intrinsics for the resection. A new camera (intrinsic) will be created." << std::endl; // Since the spherical image is only defined by its image size we can initialize its camera model. // This way the resection will be performed with valid bearing vector if (openMVG::cameras::EINTRINSIC(i_User_camera_model) == cameras::CAMERA_SPHERICAL) { optional_intrinsic = std::make_shared<cameras::Intrinsic_Spherical>(imageGray.Width(), imageGray.Height()); } } geometry::Pose3 pose; sfm::Image_Localizer_Match_Data matching_data; matching_data.error_max = dMaxResidualError; bool bSuccessfulLocalization = false; // Try to localize the image in the database thanks to its regions if (!localizer.Localize( optional_intrinsic ? static_cast<resection::SolverType>(resection_method) : resection::SolverType::DLT_6POINTS, {imageGray.Width(), imageGray.Height()}, optional_intrinsic.get(), *(query_regions.get()), pose, &matching_data)) { std::cerr << "Cannot locate the image " << *iter_image << std::endl; bSuccessfulLocalization = false; } else { const bool b_new_intrinsic = (optional_intrinsic == nullptr); // A valid pose has been found (try to refine it): // If not intrinsic as input: // init a new one from the projection matrix decomposition // Else use the existing one and consider as static. if (b_new_intrinsic) { // setup a default camera model from the found projection matrix Mat3 K, R; Vec3 t; KRt_From_P(matching_data.projection_matrix, &K, &R, &t); const double focal = (K(0,0) + K(1,1))/2.0; const Vec2 principal_point(K(0,2), K(1,2)); switch (openMVG::cameras::EINTRINSIC(i_User_camera_model)) { case cameras::PINHOLE_CAMERA: optional_intrinsic = std::make_shared<cameras::Pinhole_Intrinsic>(imageGray.Width(), imageGray.Height(),focal, principal_point(0), principal_point(1)); break; case cameras::PINHOLE_CAMERA_RADIAL1: optional_intrinsic = std::make_shared<cameras::Pinhole_Intrinsic_Radial_K1>(imageGray.Width(), imageGray.Height(),focal, principal_point(0), principal_point(1)); break; case cameras::PINHOLE_CAMERA_RADIAL3: optional_intrinsic = std::make_shared<cameras::Pinhole_Intrinsic_Radial_K3>(imageGray.Width(), imageGray.Height(),focal, principal_point(0), principal_point(1)); break; case cameras::PINHOLE_CAMERA_BROWN: optional_intrinsic = std::make_shared<cameras::Pinhole_Intrinsic_Brown_T2>(imageGray.Width(), imageGray.Height(),focal, principal_point(0), principal_point(1)); break; case cameras::PINHOLE_CAMERA_FISHEYE: optional_intrinsic = std::make_shared<cameras::Pinhole_Intrinsic_Fisheye>(imageGray.Width(), imageGray.Height(),focal, principal_point(0), principal_point(1)); break; case cameras::CAMERA_SPHERICAL: std::cerr << "The spherical camera cannot be created there. Resection of a spherical camera must be done with an existing camera model." << std::endl; break; default: std::cerr << "Error: unknown camera model: " << static_cast<int>(i_User_camera_model) << std::endl; } } if (optional_intrinsic && sfm::SfM_Localizer::RefinePose( optional_intrinsic.get(), pose, matching_data, true, b_new_intrinsic)) { bSuccessfulLocalization = true; } else { std::cerr << "Refining pose for the image " << *iter_image << " failed." << std::endl; } } #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { total_num_images++; View v(*iter_image, views.size(), views.size(), views.size(), imageGray.Width(), imageGray.Height()); if (bSuccessfulLocalization) { vec_found_poses.push_back(pose.center()); // Add the computed intrinsic to the sfm_container if (!bUseSingleIntrinsics) intrinsics[v.id_intrinsic] = optional_intrinsic; else // Make the view using the existing intrinsic id v.id_intrinsic = sfm_data.GetViews().begin()->second->id_intrinsic; // Add the computed pose to the sfm_container poses[v.id_pose] = pose; } else { v.id_intrinsic = UndefinedIndexT; v.id_pose = UndefinedIndexT; } // Add the view to the sfm_container views[v.id_view] = std::make_shared<View>(v); } } GroupSharedIntrinsics(sfm_data); std::cout << " Total poses found : " << vec_found_poses.size() << "/" << total_num_images << std::endl; // Export the found camera position in a ply. const std::string out_file_name = stlplus::create_filespec(sOutDir, "found_pose_centers", "ply"); plyHelper::exportToPly(vec_found_poses, out_file_name); // Export found camera poses along with original reconstruction in a new sfm_data file ESfM_Data flag_save; if (bExportStructure) { flag_save = ESfM_Data(ALL); } else { flag_save = ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS); } if (!Save( sfm_data, stlplus::create_filespec( sOutDir, "sfm_data_expanded.json" ).c_str(), flag_save)) { return EXIT_FAILURE; } // export also as ply if (!Save( sfm_data, stlplus::create_filespec( sOutDir, "sfm_data_expanded.ply" ).c_str(), ESfM_Data(ALL))) { return EXIT_FAILURE; } return EXIT_SUCCESS; }
19,627
C++
.cpp
455
37.773626
173
0.651871
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,780
main.cpp
openMVG_openMVG/src/software/SfMViewer/main.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <cstdlib> #include <stdio.h> #include <cmath> #include <iterator> #ifdef __APPLE__ #include <OpenGL/gl.h> #include <GLUT/glut.h> #else #ifdef _WIN32 #include <windows.h> #endif #endif #include <GLFW/glfw3.h> #include "openMVG/sfm/sfm.hpp" #include "openMVG/image/image_io.hpp" #include "third_party/cmdLine/cmdLine.h" using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::sfm; static int running = 1; static SfM_Data sfm_data; static int current_cam = -1; static float x_offset = 0.f; static float y_offset = 0.f; static float z_offset = 0.f; static float normalized_focal = 1.f; // Contiguous array of the valid camera index static std::vector<IndexT> vec_cameras; struct GLWImage { int width, height; GLuint texture; }; static std::vector< GLWImage > m_image_vector; /* close callback */ void window_close_callback(GLFWwindow* window) { running = 0; } void load_textures() { const size_t nbCams = vec_cameras.size(); m_image_vector.resize(nbCams); system::LoggerProgress my_progress_bar( nbCams, "Textures loading, Please wait..." ); for ( size_t i_cam=0; i_cam < nbCams; ++i_cam, ++my_progress_bar) { const View * view = sfm_data.GetViews().at(vec_cameras[i_cam]).get(); const std::string srcImage = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path); std::vector<unsigned char> img; int w,h,depth; if (ReadImage(srcImage.c_str(), &img, &w, &h, &depth)) { glEnable(GL_TEXTURE_2D); //std::cout << "Read image : " << sImageName << "\n" << std::endl; glDeleteTextures(1, &m_image_vector[i_cam].texture); // Create texture glGenTextures( 1, &m_image_vector[i_cam].texture); // select our current texture glBindTexture(GL_TEXTURE_2D, m_image_vector[i_cam].texture); m_image_vector[i_cam].width = w; m_image_vector[i_cam].height = h; glTexImage2D(GL_TEXTURE_2D, 0, (depth == 1) ? GL_LUMINANCE : GL_RGB, m_image_vector[i_cam].width, m_image_vector[i_cam].height, 0, (depth == 1) ? GL_LUMINANCE : GL_RGB, GL_UNSIGNED_BYTE, &img[0]); glBindTexture(GL_TEXTURE_2D, m_image_vector[i_cam].texture); } } } /* new window size */ void reshape( GLFWwindow* window, int width, int height ) { glViewport( 0, 0, (GLint) width, (GLint) height ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); GLfloat zNear = 1e-2; GLfloat zFar = 1e5; GLfloat aspect = float(width)/float(height); GLfloat fH = std::tan( float(60 / 360.0f * 3.14159f) ) * zNear; GLfloat fW = fH * aspect; glFrustum( -fW, fW, -fH, fH, zNear, zFar ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); } void key(GLFWwindow* window, int k, int scancode, int action, int mod) { if (action != GLFW_PRESS ) { return; } switch (k) { case GLFW_KEY_ESCAPE: running = 0; break; case GLFW_KEY_LEFT: --current_cam; if (current_cam < 0) { current_cam = vec_cameras.size()-1; } break; case GLFW_KEY_RIGHT: ++current_cam; if (current_cam >= static_cast<int>(vec_cameras.size())) { current_cam = 0; } break; case GLFW_KEY_R: x_offset = 0.f; y_offset = 0.f; z_offset = 0.f; normalized_focal = 1.f; break; case GLFW_KEY_Q: z_offset -= 0.1f; break; case GLFW_KEY_E: z_offset += 0.1f; break; case GLFW_KEY_W: y_offset += 0.1f; break; case GLFW_KEY_S: y_offset -= 0.1f; break; case GLFW_KEY_A: x_offset += 0.1f; break; case GLFW_KEY_D: x_offset -= 0.1f; break; case GLFW_KEY_KP_SUBTRACT: normalized_focal -= 0.1f; break; case GLFW_KEY_KP_ADD: normalized_focal += 0.1f; break; default: return; } } // the conversion matrix from OpenGL default coordinate system // to the camera coordinate system: // [ 1 0 0 0] * [ x ] = [ x ] // 0 -1 0 0 y -y // 0 0 -1 0 z -z // 0 0 0 1 1 1 const GLfloat m_convert[4][4] = { {1.f, 0.f, 0.f, 0.f}, {0.f, -1.f, 0.f, 0.f}, {0.f, 0.f, -1.f, 0.f}, {0.f, 0.f, 0.f, 1.f}}; //Local to World static openMVG::Mat4 l2w_Camera(const Mat3 & R, const Vec3 & t) { //World to Local /// given rotation matrix R and translation vector t, /// column-major matrix m is equal to: /// [ R11 R12 R13 t.x ] /// | R21 R22 R23 t.y | /// | R31 R32 R33 t.z | /// [ 0.0 0.0 0.0 1.0 ] //Local to World => Coordinates of the camera in the 3d space openMVG::Mat4 l2wmat = Mat4::Identity(); l2wmat.block(0,0,3,4) = HStack(R,t); return l2wmat; } /* OpenGL draw function & timing */ static void draw(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); { // convert opengl coordinates into the document information coordinates glPushMatrix(); glMultMatrixf((GLfloat*)m_convert); // apply view offset openMVG::Mat4 offset_w = l2w_Camera(Mat3::Identity(), Vec3(x_offset,y_offset,z_offset)); glMultMatrixd((GLdouble*)offset_w.data()); // then apply current camera transformation const View * view = sfm_data.GetViews().at(vec_cameras[current_cam]).get(); const Pose3 pose = sfm_data.GetPoseOrDie(view); const openMVG::Mat4 l2w = l2w_Camera(pose.rotation(), pose.translation()); glPushMatrix(); glMultMatrixd((GLdouble*)l2w.data()); glPointSize(3); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); //Draw Structure in GREEN (as seen from the current camera) glBegin(GL_POINTS); glColor3f(0.f,1.f,0.f); for (const auto & landmark_iter : sfm_data.GetLandmarks()) { const Landmark & landmark = landmark_iter.second; glVertex3d(landmark.X(0), landmark.X(1), landmark.X(2)); } glEnd(); glDisable(GL_CULL_FACE); for (int i_cam=0; i_cam < static_cast<int>(vec_cameras.size()); ++i_cam) { const View * view = sfm_data.GetViews().at(vec_cameras[i_cam]).get(); const Pose3 pose = sfm_data.GetPoseOrDie(view); const IntrinsicBase * cam = sfm_data.GetIntrinsics().at(view->id_intrinsic).get(); if (isPinhole(cam->getType())) { const Pinhole_Intrinsic * camPinhole = dynamic_cast<const Pinhole_Intrinsic*>(cam); // Move frame to draw the camera i_cam by applying its inverse transformation // Warning: translation has to be "fixed" to remove the current camera rotation // Fix camera_i translation with current camera rotation inverse const Vec3 trans = pose.rotation().transpose() * pose.translation(); // compute inverse transformation matrix from local to world const openMVG::Mat4 l2w_i = l2w_Camera(pose.rotation().transpose(), -trans); // stack it and use it glPushMatrix(); glMultMatrixd((GLdouble*)l2w_i.data()); // 1. Draw optical center (RED) and image center (BLUE) glPointSize(3); glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glBegin(GL_POINTS); glColor3f(1.f,0.f,0.f); glVertex3f(0, 0, 0); // optical center glColor3f(0.f,0.f,1.f); glVertex3f(0, 0, normalized_focal); // image center glEnd(); // compute image corners coordinated with normalized focal (f=normalized_focal) const int w = camPinhole->w(); const int h = camPinhole->h(); const double focal = camPinhole->focal(); // use principal point to adjust image center const Vec2 pp = camPinhole->principal_point(); const Vec3 c1( -pp[0]/focal * normalized_focal, (-pp[1]+h)/focal * normalized_focal, normalized_focal); const Vec3 c2((-pp[0]+w)/focal * normalized_focal, (-pp[1]+h)/focal * normalized_focal, normalized_focal); const Vec3 c3((-pp[0]+w)/focal * normalized_focal, -pp[1]/focal * normalized_focal, normalized_focal); const Vec3 c4( -pp[0]/focal * normalized_focal, -pp[1]/focal * normalized_focal, normalized_focal); // 2. Draw thumbnail if (i_cam == current_cam) { glEnable(GL_TEXTURE_2D); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, m_image_vector[i_cam].texture); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); if (i_cam == current_cam) { glColor4f(0.5f,0.5f,0.5f, 0.7f); } else { glColor4f(0.5f,0.5f,0.5f, 0.5f); } glBegin(GL_QUADS); glTexCoord2d(0.0,1.0); glVertex3d(c1[0], c1[1], c1[2]); glTexCoord2d(1.0,1.0); glVertex3d(c2[0], c2[1], c2[2]); glTexCoord2d(1.0,0.0); glVertex3d(c3[0], c3[1], c3[2]); glTexCoord2d(0.0,0.0); glVertex3d(c4[0], c4[1], c4[2]); glEnd(); glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); } // 3. Draw camera cone if (i_cam == current_cam) { glColor3f(1.f,1.f,0.f); } else { glColor3f(1.f,0.f,0.f); } glBegin(GL_LINES); glVertex3d(0.0,0.0,0.0); glVertex3d(c1[0], c1[1], c1[2]); glVertex3d(0.0,0.0,0.0); glVertex3d(c2[0], c2[1], c2[2]); glVertex3d(0.0,0.0,0.0); glVertex3d(c3[0], c3[1], c3[2]); glVertex3d(0.0,0.0,0.0); glVertex3d(c4[0], c4[1], c4[2]); glVertex3d(c1[0], c1[1], c1[2]); glVertex3d(c2[0], c2[1], c2[2]); glVertex3d(c2[0], c2[1], c2[2]); glVertex3d(c3[0], c3[1], c3[2]); glVertex3d(c3[0], c3[1], c3[2]); glVertex3d(c4[0], c4[1], c4[2]); glVertex3d(c4[0], c4[1], c4[2]); glVertex3d(c1[0], c1[1], c1[2]); glEnd(); glPopMatrix(); // go back to current camera frame } } glPopMatrix(); // go back to (document +offset) frame glPopMatrix(); // go back to identity } } int main(int argc, char *argv[]) { CmdLine cmd; std::string sSfM_Data_Filename; cmd.add( make_option('i', sSfM_Data_Filename, "sfmdata") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--sfmdata filename, the SfM_Data file to read]\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } // Read the SfM scene if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(ALL))) { std::cerr << std::endl << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl; return EXIT_FAILURE; } // List valid camera (view that have a pose & a valid intrinsic data) for (Views::const_iterator iter = sfm_data.GetViews().begin(); iter != sfm_data.GetViews().end(); ++iter) { const View * view = iter->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; vec_cameras.push_back(iter->first); } current_cam = 0; std::cout << "Press left or right key to navigate between cameras." << std::endl << "Move viewpoint with Q,W,E,A,S,D" << std::endl << "Change Normalized focal (camera cones size) with '+' and '-'" << std::endl << "Reset viewpoint position with R" << std::endl << "Esc to quit" << std::endl; //-- Create the GL window context GLFWwindow* window; int width, height; if ( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); exit( EXIT_FAILURE ); } glfwWindowHint(GLFW_DEPTH_BITS, 16); window = glfwCreateWindow( 1000, 600, "SfmViewer", nullptr, nullptr ); if (!window) { fprintf( stderr, "Failed to open GLFW window\n" ); glfwTerminate(); exit( EXIT_FAILURE ); } // Set callback functions glfwSetWindowCloseCallback(window, window_close_callback); glfwSetWindowSizeCallback(window, reshape); glfwSetKeyCallback(window, key); glfwMakeContextCurrent(window); glfwSwapInterval( 1 ); glfwGetWindowSize(window, &width, &height); reshape(window, width, height); load_textures(); // Main loop while (running) { // Draw SfM Scene draw(); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } // Terminate GLFW glfwTerminate(); // Exit program exit( EXIT_SUCCESS ); }
12,724
C++
.cpp
358
30.659218
114
0.63348
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,781
main_VO.cpp
openMVG_openMVG/src/software/VO/main_VO.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2014 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/image/image_io.hpp" #include "openMVG/features/feature.hpp" #if defined HAVE_OPENGL #include "software/VO/CGlWindow.hpp" #endif #include "software/VO/Monocular_VO.hpp" #include "software/VO/Tracker.hpp" #if defined HAVE_OPENCV #include "software/VO/Tracker_opencv_klt.hpp" #endif #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cstdlib> #include <iostream> using namespace openMVG; int main(int argc, char **argv) { std::cout << "VISUAL ODOMETRY -- Tracking demo --" << std::endl; CmdLine cmd; std::string sImaDirectory = ""; std::string sOutFile = ""; unsigned int uTracker = 0; unsigned int uTrackerPointCount = 1500; cmd.add( make_option('i', sImaDirectory, "imadir") ); cmd.add( make_option('t', uTracker, "tracker") ); cmd.add( make_option('o', sOutFile, "output_file") ); cmd.add( make_option('p', uTrackerPointCount, "point_count") ); cmd.add( make_switch('d', "disable_tracking_display") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--imadir path] \n" << "[-o|--output_file path] The output tracking saved as a sfm_data file (landmark observations).\n" << "[-t|--tracker Used tracking interface] \n" << "\t 0: Feature matching based tracking (default); Fast detector + Dipole descriptor, \n" #if defined HAVE_OPENCV << "\t 1: Feature tracking based tracking; Fast + KLT pyramidal tracking. \n" #endif << "[-p|--point_count] Number of points to track. (default: " << uTrackerPointCount << ")\n" << "[-d|--disable_tracking_display] Disable tracking display \n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } std::cout << " You called : " << std::endl << argv[0] << std::endl << "--imageDirectory " << sImaDirectory << std::endl << "--output_file " << sOutFile << std::endl << "--point_count " << uTrackerPointCount << std::endl << "--tracker " << uTracker << std::endl << "--disable_tracking_display " << static_cast<int>(cmd.used('d')) << std::endl; if (sImaDirectory.empty() || !stlplus::is_folder(sImaDirectory)) { std::cerr << "\nIt is an invalid input directory" << std::endl; return EXIT_FAILURE; } if (sOutFile.empty()) { std::cerr << "\nPlease use a valid filename for the output_file option (i.e: <PATH>/sfm_data.bin)." << std::endl; return EXIT_FAILURE; } #if defined HAVE_OPENGL if ( !glfwInit() ) { return EXIT_FAILURE; } const bool disable_tracking_display = cmd.used('d'); //-- CGlWindow window; GLuint text2D; #endif //--------------------------------------- // VO: Visual Odometry //--------------------------------------- // Loop over the image sequence // . detect keypoints // . show them in an openGL window // . track features // . perform VO std::vector<std::string> vec_image = stlplus::folder_files(sImaDirectory); // clean invalid image file { std::vector<std::string> vec_image_; for (size_t i = 0; i < vec_image.size(); ++i) { if (openMVG::image::GetFormat(vec_image[i].c_str()) != openMVG::image::Unknown) vec_image_.emplace_back(vec_image[i]); } vec_image_.swap(vec_image); } std::sort(vec_image.begin(), vec_image.end()); image::Image<unsigned char> currentImage; using namespace openMVG::VO; // Initialize the tracker interface std::unique_ptr<Abstract_Tracker> tracker_ptr; switch (uTracker) { case 0: tracker_ptr.reset(new Tracker_fast_dipole); break; #if defined HAVE_OPENCV case 1: tracker_ptr.reset(new Tracker_opencv_KLT); break; #endif default: std::cerr << "Unknow tracking method" << std::endl; return EXIT_FAILURE; } if (!tracker_ptr) { std::cerr << "Cannot instantiate the Feature tracking interface" << std::endl; return EXIT_FAILURE; } // Initialize the monocular tracking framework VO_Monocular monocular_vo(tracker_ptr.get(), uTrackerPointCount); size_t frameId = 0; for (std::vector<std::string>::const_iterator iterFile = vec_image.begin(); iterFile != vec_image.end(); ++iterFile, ++frameId) { const std::string sImageFilename = stlplus::create_filespec( sImaDirectory, *iterFile ); if (openMVG::image::ReadImage( sImageFilename.c_str(), &currentImage)) { #if defined HAVE_OPENGL if (window._height < 0) { // no window created yet, initialize it with the first frame const double aspect_ratio = currentImage.Width() / (double)currentImage.Height(); window.Init(640, 640 / aspect_ratio, "VisualOdometry--TrackingViewer"); glGenTextures(1, &text2D); //allocate the memory for texture glBindTexture(GL_TEXTURE_2D, text2D); //Binding the texture glEnable(GL_TEXTURE_2D); //Enable texture glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, currentImage.Width(), currentImage.Height(), 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, currentImage.data()); } glBindTexture(GL_TEXTURE_2D, text2D); //Binding the texture glEnable(GL_TEXTURE_2D); //Enable texture //-- Update the openGL texture with the current frame pixel values glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, currentImage.Width(), currentImage.Height(), GL_LUMINANCE, GL_UNSIGNED_BYTE, currentImage.data()); //-- Draw the current image window.SetOrtho(currentImage.Width(), currentImage.Height()); window.DrawFullScreenTexQuad(currentImage.Width(), currentImage.Height()); glDisable(GL_TEXTURE_2D); // Clear the depth buffer so the drawn image become the background glClear(GL_DEPTH_BUFFER_BIT); glDisable(GL_LIGHTING); #endif //-- //-- Feature tracking // . track features // . if some tracks are cut, detect and insert new features //-- monocular_vo.nextFrame(currentImage, frameId); #if defined HAVE_OPENGL //-- // Draw feature trajectories //-- glColor3f(0.f, 1.f, 0.f); glLineWidth(2.f); if (!disable_tracking_display) { for (size_t idx = 0; idx < monocular_vo.landmark_.size(); ++idx) { if (std::find(monocular_vo.trackedLandmarkIds_.cbegin(), monocular_vo.trackedLandmarkIds_.cend(), idx) == monocular_vo.trackedLandmarkIds_.cend()) continue; const Landmark & landmark = monocular_vo.landmark_[idx]; if (landmark.obs_.back().frameId_ == frameId && landmark.obs_.size() > 1 ) { const std::deque<Measurement> & obs = landmark.obs_; std::deque<Measurement>::const_reverse_iterator iter = obs.rbegin(), iterEnd = obs.rend(); int limit = 10; glBegin(GL_LINE_STRIP); glColor3f(0.f, 1.f, 0.f); for (; iter != iterEnd && limit >=0; ++iter, --limit) { const Vec2f & p0 = iter->pos_; glVertex2f(p0(0), p0(1)); } glEnd(); // draw the current tracked point { std::deque<Measurement>::const_reverse_iterator iter = obs.rbegin(); glPointSize(4.0f); glBegin(GL_POINTS); glColor3f(1.f, 1.f, 0.f); // Yellow const Vec2f & p0 = iter->pos_; glVertex2f(p0(0), p0(1)); glEnd(); } } else // Draw the new initialized point { glPointSize(10.0f); if ( landmark.obs_.size() == 1 ) { const std::deque<Measurement> & obs = landmark.obs_; glBegin(GL_POINTS); glColor3f(0.f, 0.f, 1.f); // Blue std::deque<Measurement>::const_iterator iter = obs.begin(); const Vec2f & p0 = iter->pos_; glVertex2f(p0(0), p0(1)); glEnd(); } } } } glFlush(); window.Swap(); // Swap openGL buffer #endif } } openMVG::sfm::SfM_Data sfm_data; ConvertVOLandmarkToSfMDataLandmark(monocular_vo.landmark_, sfm_data.structure); std::cout << "Found SFM #landmarks: " << sfm_data.structure.size() << std::endl; if (!Save(sfm_data, sOutFile, openMVG::sfm::ESfM_Data(openMVG::sfm::ALL))) return EXIT_FAILURE; #if defined HAVE_OPENGL glfwTerminate(); #endif return 0; }
9,249
C++
.cpp
240
32.020833
117
0.614184
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,782
VOViewerDrawableElements.cpp
openMVG_openMVG/src/software/VO/AlternativeVO/VOViewerDrawableElements.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2016 Romuald Perrot // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "software/VO/AlternativeVO/VOViewerDrawableElements.hpp" namespace alternative_vo { const QColor VOViewerLine::DEFAULT_LINE_COLOR = Qt::green; const QColor VOViewerPoint::DEFAULT_TRACKED_POINT_COLOR = Qt::yellow; const QColor VOViewerPoint::DEFAULT_NEW_POINT_COLOR = Qt::blue; }
610
C++
.cpp
12
49.333333
76
0.777027
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,783
VOFolderProcessor.cpp
openMVG_openMVG/src/software/VO/AlternativeVO/VOFolderProcessor.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2016 Romuald Perrot // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "software/VO/AlternativeVO/VOFolderProcessor.hpp" #include "software/VO/Abstract_Tracker.hpp" #include "software/VO/Tracker.hpp" #if defined HAVE_OPENCV #include "software/VO/Tracker_opencv_klt.hpp" #endif #include "openMVG/image/image_io.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" namespace alternative_vo { VOFolderProcessor::VOFolderProcessor( const std::string & inputFolder ) : m_input_folder( inputFolder ) , m_current_file_ID( 0 ) { m_input_files = stlplus::folder_files( m_input_folder ); // clean invalid image file { std::vector<std::string> vec_image_; for ( size_t i = 0; i < m_input_files.size(); ++i ) { if ( openMVG::image::GetFormat( m_input_files[i].c_str() ) != openMVG::image::Unknown ) { vec_image_.push_back( m_input_files[i] ); } } vec_image_.swap( m_input_files ); } std::sort( m_input_files.begin(), m_input_files.end() ); // Initialize the Visual Odometry interface m_tracker.reset( new openMVG::VO::Tracker_fast_dipole ); m_monocular_vo.reset( new openMVG::VO::VO_Monocular( m_tracker.get(), 1500 ) ); } /** * @brief Reset processing to the begining */ void VOFolderProcessor::Reset( void ) { m_current_file_ID = 0; } /** * @brief get current filename beeing processed */ std::string VOFolderProcessor::CurrentFileName( void ) { return m_input_files[ m_current_file_ID ]; } /** * @brief get full filename for a given id * @retval empty string if id is out of range * @retval full path for given id if id is in valid range */ std::string VOFolderProcessor::FullFileName( const size_t id ) { if (id >= m_input_files.size() ) { return ""; } else { return stlplus::create_filespec( m_input_folder, m_input_files[ id ] ); } } /** * @brief Get total number of frame */ size_t VOFolderProcessor::NbFrame( void ) { return m_input_files.size(); } /** * @brief get current frame ID */ size_t VOFolderProcessor::CurrentFrameID( void ) { return m_current_file_ID; } /** * @brief Try to step forward * @retval false if process has ended * @retval true if new image could be processed */ bool VOFolderProcessor::StepForward( void ) { if (m_current_file_ID + 1 >= m_input_files.size() ) { return false; } else { const std::string sImageFilename = stlplus::create_filespec( m_input_folder, m_input_files[ m_current_file_ID ] ); openMVG::image::Image<unsigned char> currentImage; if ( openMVG::image::ReadImage( sImageFilename.c_str(), &currentImage ) ) { m_monocular_vo->nextFrame( currentImage , m_current_file_ID ); } ++m_current_file_ID; return true; } } /** * @brief Get current position of the tracked points */ std::vector< VOViewerPoint > VOFolderProcessor::GetCurrentTrackedPoints( void ) const { std::vector< VOViewerPoint > res; res.reserve(m_monocular_vo->landmark_.size()); for ( size_t idx = 0; idx < m_monocular_vo->landmark_.size(); ++idx ) { if ( std::find( m_monocular_vo->trackedLandmarkIds_.begin(), m_monocular_vo->trackedLandmarkIds_.end(), idx ) == m_monocular_vo->trackedLandmarkIds_.end() ) { continue; } const openMVG::VO::Landmark & landmark = m_monocular_vo->landmark_[idx]; if ( landmark.obs_.back().frameId_ == m_current_file_ID - 1 && landmark.obs_.size() > 1 ) { const std::deque<openMVG::VO::Measurement> & obs = landmark.obs_; // draw the current tracked point { std::deque<openMVG::VO::Measurement>::const_reverse_iterator iter = obs.rbegin(); VOViewerPoint cur_tracked; cur_tracked.m_color = VOViewerPoint::DEFAULT_TRACKED_POINT_COLOR; cur_tracked.m_pt = iter->pos_; res.push_back( cur_tracked ); } } } return res; } /** * @brief Get current position of the newly created points in the last processed frame */ std::vector< VOViewerPoint > VOFolderProcessor::GetCreatedPoints( void ) const { std::vector< VOViewerPoint > res; res.reserve(m_monocular_vo->landmark_.size()); for ( size_t idx = 0; idx < m_monocular_vo->landmark_.size(); ++idx ) { if ( std::find( m_monocular_vo->trackedLandmarkIds_.begin(), m_monocular_vo->trackedLandmarkIds_.end(), idx ) == m_monocular_vo->trackedLandmarkIds_.end() ) { continue; } const openMVG::VO::Landmark & landmark = m_monocular_vo->landmark_[idx]; if ( landmark.obs_.back().frameId_ == m_current_file_ID - 1 && landmark.obs_.size() > 1 ) { } else // Draw the new initialized point { if ( landmark.obs_.size() == 1 ) { const std::deque<openMVG::VO::Measurement> & obs = landmark.obs_; std::deque<openMVG::VO::Measurement>::const_iterator iter = obs.begin(); VOViewerPoint cur_created; cur_created.m_color = VOViewerPoint::DEFAULT_NEW_POINT_COLOR; cur_created.m_pt = iter->pos_; res.push_back( cur_created ); } } } return res; } /** * @brief Get for each tracked points, their full trajectories */ std::vector< VOViewerLine > VOFolderProcessor::GetCurrentTrackTrajectories( void ) const { std::vector< VOViewerLine > res; res.reserve(m_monocular_vo->landmark_.size()); for ( size_t idx = 0; idx < m_monocular_vo->landmark_.size(); ++idx ) { if ( std::find( m_monocular_vo->trackedLandmarkIds_.begin(), m_monocular_vo->trackedLandmarkIds_.end(), idx ) == m_monocular_vo->trackedLandmarkIds_.end() ) { continue; } const openMVG::VO::Landmark & landmark = m_monocular_vo->landmark_[idx]; if ( landmark.obs_.back().frameId_ == m_current_file_ID - 1 && landmark.obs_.size() > 1 ) { const std::deque<openMVG::VO::Measurement> & obs = landmark.obs_; std::deque<openMVG::VO::Measurement>::const_reverse_iterator iter = obs.rbegin(); std::deque<openMVG::VO::Measurement>::const_reverse_iterator iterEnd = obs.rend(); /* Trajectories */ int limit = 10; VOViewerLine cur_traj; cur_traj.m_pts.reserve(limit); cur_traj.m_color = VOViewerLine::DEFAULT_LINE_COLOR; for (; iter != iterEnd && limit >= 0; ++iter, --limit ) { const openMVG::Vec2f & p0 = iter->pos_; cur_traj.m_pts.push_back( p0 ); } res.push_back( cur_traj ); } } return res; } }
6,704
C++
.cpp
206
28.456311
118
0.661408
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,785
MainWindow.cpp
openMVG_openMVG/src/software/VO/AlternativeVO/MainWindow.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2016 Romuald Perrot // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "MainWindow.hpp" #include <QVBoxLayout> #include <QFileDialog> #include <QMessageBox> #include <QCoreApplication> #include <QMenuBar> namespace alternative_vo { /** * @brief default ctr */ MainWindow::MainWindow( ) : m_vo_processor( nullptr ) { BuildInterface(); BuildMenus(); MakeConnections(); m_control_panel->EnableButtons( false ); resize( 1024 , 768 ); } /** * @brief Action to be executed when user open an image folder */ void MainWindow::onMenuOpenImageFolder( void ) { QString folder = QFileDialog::getExistingDirectory( this , "Select Input image folder" , QDir::homePath() ); if ( ! ( folder.isNull() || folder.isEmpty() ) ) { m_vo_processor = std::make_shared< VOFolderProcessor >( folder.toStdString() ); if (m_vo_processor->NbFrame() == 0 ) { QMessageBox::critical( this , "Input Error" , "Provided folder does not contain any valid image file" ); m_control_panel->EnableButtons( true ); // m_control_panel->EnablePlayBtn( false ); m_vo_processor = nullptr; } else { m_control_panel->EnableButtons( true ); } } } /** * @brief Action to be executed when user want to quit the application * @note : Do nothing, users should love our app and there's no reason to quit us. */ void MainWindow::onMenuQuit( void ) { QCoreApplication::quit(); } /** * Action to be executed when user press play button */ void MainWindow::onPlayVOProcess( void ) { if (m_timer ) { m_timer->start( 40 ); // 30 ms -> 25 fps } else { m_timer = new QTimer; connect( m_timer , SIGNAL( timeout() ) , this , SLOT( onTimerTick() ) ); m_timer->start( 40 ); } } /** * Action to be executed when user press stop/pause button */ void MainWindow::onStopVOProcess( void ) { if (m_timer ) { m_timer->stop(); } } /** * Action to be executed when user press Forward button */ void MainWindow::onStepForwardVOProcess( void ) { if (m_vo_processor ) { const size_t curr_ID = m_vo_processor->CurrentFrameID( ); if (m_vo_processor->StepForward() ) { // Has computed a new frame, get, update image and it's corresponding landmarks QImage img( m_vo_processor->FullFileName( curr_ID ).c_str() ); // Get all points std::vector< VOViewerPoint > created = m_vo_processor->GetCreatedPoints(); std::vector< VOViewerPoint > tracked = m_vo_processor->GetCurrentTrackedPoints(); created.insert( created.end() , tracked.begin() , tracked.end() ); // Get all lines const std::vector< VOViewerLine > trajs = m_vo_processor->GetCurrentTrackTrajectories(); m_viewer_panel->SetImage( img , trajs , created ); } else { // Nothing can be done more, stop processing m_control_panel->EnablePlayBtn( false ); m_control_panel->EnableStopBtn( false ); m_control_panel->EnableForwardBtn( false ); } // Disable further update if we are at the end of the process if (m_vo_processor->CurrentFrameID() >= m_vo_processor->NbFrame() ) { m_control_panel->EnablePlayBtn( false ); m_control_panel->EnableStopBtn( false ); m_control_panel->EnableForwardBtn( false ); } } } /** * Action to be executed when user press Reset button * @note Reset is when user want to start again the process */ void MainWindow::onResetVOProcess( void ) { if (m_vo_processor ) { m_vo_processor->Reset(); m_control_panel->EnableButtons( true ); } } void MainWindow::BuildInterface() { QWidget * dummy = new QWidget; m_control_panel = new ControlButtonsPanel( this ); m_viewer_panel = new VOViewerPanel( this ); QVBoxLayout * mainLayout = new QVBoxLayout; mainLayout->addWidget( m_viewer_panel ); mainLayout->addStretch( ); mainLayout->addWidget( m_control_panel ); dummy->setLayout( mainLayout ); setCentralWidget( dummy ); } void MainWindow::BuildMenus() { m_file_menu = new QMenu( "File" ); m_folder_open_act = new QAction( "Open image folder" , this ); m_quit_act = new QAction( "Quit" , this ); m_file_menu->addAction( m_folder_open_act ); m_file_menu->addSeparator( ); m_file_menu->addAction( m_quit_act ); QMenuBar * menu_bar = menuBar(); menu_bar->addMenu( m_file_menu ); } void MainWindow::MakeConnections() { // Menus elts connect( m_folder_open_act , SIGNAL( triggered() ) , this , SLOT( onMenuOpenImageFolder() ) ); connect( m_quit_act , SIGNAL( triggered() ) , this , SLOT( onMenuQuit() ) ); // Control panel connect( m_control_panel , SIGNAL( hasClickedPlay() ) , this , SLOT( onPlayVOProcess() ) ); connect( m_control_panel , SIGNAL( hasClickedStop() ) , this , SLOT( onStopVOProcess() ) ); connect( m_control_panel , SIGNAL( hasClickedReset() ) , this , SLOT( onResetVOProcess() ) ); connect( m_control_panel , SIGNAL( hasClickedForward() ) , this , SLOT( onStepForwardVOProcess() ) ); } void MainWindow::onTimerTick() { if ( ! m_vo_processor ) { if ( m_timer ) { m_timer->stop(); } } else { onStepForwardVOProcess(); } } }
5,380
C++
.cpp
178
26.983146
110
0.679768
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,786
VOViewerPanel.cpp
openMVG_openMVG/src/software/VO/AlternativeVO/VOViewerPanel.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2016 Romuald Perrot // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "software/VO/AlternativeVO/VOViewerPanel.hpp" #include <QHBoxLayout> #include <QPainter> namespace alternative_vo { VOViewerPanel::VOViewerPanel( QWidget * parent ) { BuildInterface(); MakeConnections(); } void VOViewerPanel::SetImage( QImage & img ) { m_image_view->setPixmap( QPixmap::fromImage( img ) ); } /** * @brief Set an image and draw some elements on it * @param lines List of lines to draw */ void VOViewerPanel::SetImage( QImage & img , const std::vector< VOViewerLine > & lines , const std::vector< VOViewerPoint > & points ) { QPixmap pmap = QPixmap::fromImage( img ); QPainter p( & pmap ); // Draw lines for (size_t i = 0; i < lines.size(); ++i ) { p.setPen( lines[i].m_color ); const VOViewerLine & cur_line = lines[ i ]; if (cur_line.m_pts.size() > 0 ) { openMVG::Vec2f prev_pt = cur_line.m_pts[ 0 ]; for (size_t id_point = 1; id_point < cur_line.m_pts.size(); ++id_point ) { openMVG::Vec2f cur_pt = cur_line.m_pts[ id_point ]; p.drawLine( QPoint( prev_pt( 0 ) , prev_pt( 1 ) ) , QPoint( cur_pt( 0 ) , cur_pt( 1 ) ) ); prev_pt = cur_pt; } } } // Draw points for (size_t i = 0; i < points.size(); ++i ) { const VOViewerPoint & cur_pt = points[ i ]; p.setPen( cur_pt.m_color ); p.drawPoint( QPoint( cur_pt.m_pt( 0 ) , cur_pt.m_pt( 1 ) ) ); } m_image_view->setPixmap( pmap ); } void VOViewerPanel::BuildInterface( void ) { QHBoxLayout * mainLayout = new QHBoxLayout; m_image_view = new QLabel( this ); mainLayout->addWidget( m_image_view ); setLayout( mainLayout ); } void VOViewerPanel::MakeConnections( void ) { } }
1,999
C++
.cpp
63
28.47619
134
0.657068
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,787
ControlButtonsPanel.cpp
openMVG_openMVG/src/software/VO/AlternativeVO/ControlButtonsPanel.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2016 Romuald Perrot // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "software/VO/AlternativeVO/ControlButtonsPanel.hpp" #include <QHBoxLayout> namespace alternative_vo { ControlButtonsPanel::ControlButtonsPanel( QWidget * parent ) : QWidget( parent ) { BuildInterface(); MakeConnections(); } /** * @brief Enable/disable all buttons * @param enabled True to enable, false to disable */ void ControlButtonsPanel::EnableButtons( const bool enabled ) { m_btn_forward->setEnabled( enabled ); m_btn_play->setEnabled( enabled ); m_btn_stop->setEnabled( enabled ); m_btn_reset->setEnabled( enabled ); } /** * @brief Enable/disable play button * @param enabled True to enable, false to disable */ void ControlButtonsPanel::EnablePlayBtn( const bool enabled ) { m_btn_play->setEnabled( enabled ); } /** * @brief Enable/disable stop button * @param enabled True to enable, false to disable */ void ControlButtonsPanel::EnableStopBtn( const bool enabled ) { m_btn_stop->setEnabled( enabled ); } /** * @brief Enable/disable forward button * @param enabled True to enable, false to disable */ void ControlButtonsPanel::EnableForwardBtn( const bool enabled ) { m_btn_forward->setEnabled( enabled ); } /** * @brief Enable/disable reset button * @param enabled True to enable, false to disable */ void ControlButtonsPanel::EnableResetBtn( const bool enabled ) { m_btn_reset->setEnabled( enabled ); } // Action executed when user click play button void ControlButtonsPanel::onClickPlayBtn( void ) { emit hasClickedPlay(); } // Action executed when user click stop button void ControlButtonsPanel::onClickStopBtn( void ) { emit hasClickedStop(); } // Action executed when user click forward button void ControlButtonsPanel::onClickForwardBtn( void ) { emit hasClickedForward(); } // Action executed when user click reset button void ControlButtonsPanel::onClickResetBtn( void ) { emit hasClickedReset(); } void ControlButtonsPanel::BuildInterface( void ) { m_btn_reset = new QPushButton( "Reset" , this ); m_btn_stop = new QPushButton( "Stop" , this ); m_btn_play = new QPushButton( "Play" , this ); m_btn_forward = new QPushButton( "Forward" , this ); QHBoxLayout * mainLayout = new QHBoxLayout; mainLayout->addWidget( m_btn_reset ); mainLayout->addWidget( m_btn_stop ); mainLayout->addWidget( m_btn_play ); mainLayout->addWidget( m_btn_forward ); setLayout( mainLayout ); } void ControlButtonsPanel::MakeConnections( void ) { connect( m_btn_forward , SIGNAL( clicked() ) , this , SLOT( onClickForwardBtn() ) ); connect( m_btn_play , SIGNAL( clicked() ) , this , SLOT( onClickPlayBtn() ) ); connect( m_btn_reset , SIGNAL( clicked() ) , this , SLOT( onClickResetBtn() ) ); connect( m_btn_stop , SIGNAL( clicked() ) , this , SLOT( onClickStopBtn() ) ); } }
3,071
C++
.cpp
99
29.242424
86
0.745344
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,788
matchingpairgraphicsview.cpp
openMVG_openMVG/src/software/ui/SfM/adjacency_matrix_viewer/matchingpairgraphicsview.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 <Zillow Inc.> Pierre Moulon // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "matchingpairgraphicsview.h" #include "pairgraphicsitem.h" #include "mainframe.h" #include <QByteArray> #include <QSvgWidget> #ifndef QT_NO_WHEELEVENT #include <QWheelEvent> #endif #include "openMVG/matching/svg_matches.hpp" MatchingPairGraphicsView::MatchingPairGraphicsView ( MainFrame *v, const Document & doc ) : QGraphicsView(), main_frame(v), doc(doc) { } #ifndef QT_NO_WHEELEVENT void MatchingPairGraphicsView::wheelEvent(QWheelEvent *e) { if (e->modifiers() & Qt::ControlModifier) { if (e->delta() > 0) main_frame->zoomIn(6); else main_frame->zoomOut(6); e->accept(); } else { QGraphicsView::wheelEvent(e); } } #endif void MatchingPairGraphicsView::mousePressEvent(QMouseEvent * event) { const QGraphicsItem *item = itemAt(event->pos()); if (item) { const PairGraphicsItem * pair_item = dynamic_cast<const PairGraphicsItem*>(item); if (pair_item) { // Launch here a viewer of the pair matches const unsigned int I = pair_item->get_x(); const unsigned int J = pair_item->get_y(); using namespace openMVG::matching; const IndMatches & pairwise_matches = doc.matches_provider->pairWise_matches_.at(std::make_pair(I,J)); if (!pairwise_matches.empty()) { using namespace openMVG::sfm; using namespace openMVG::features; const openMVG::sfm::View * view_I = doc.sfm_data.GetViews().at(I).get(); const std::string sView_I = stlplus::create_filespec(doc.sfm_data.s_root_path, view_I->s_Img_path); const openMVG::sfm::View * view_J = doc.sfm_data.GetViews().at(J).get(); const std::string sView_J = stlplus::create_filespec(doc.sfm_data.s_root_path, view_J->s_Img_path); // Show pairwise correspondences const bool bVertical = false; const std::string svg_string = Matches2SVGString ( sView_I, {view_I->ui_width, view_I->ui_height}, doc.feats_provider->getFeatures(view_I->id_view), sView_J, {view_J->ui_width, view_J->ui_height}, doc.feats_provider->getFeatures(view_J->id_view), pairwise_matches, bVertical ); QSvgWidget *svg = new QSvgWidget; svg->load(QByteArray(svg_string.c_str())); std::ostringstream ofs; ofs << view_I->s_Img_path << " " << view_J->s_Img_path << " #Matches: " << pairwise_matches.size(); svg->setWindowTitle( QString::fromStdString(ofs.str())); svg->show(); } } } QGraphicsView::mousePressEvent(event); // this forwards the event to the item }
3,016
C++
.cpp
86
29.290698
86
0.650532
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,790
pairgraphicsitem.cpp
openMVG_openMVG/src/software/ui/SfM/adjacency_matrix_viewer/pairgraphicsitem.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 <Zillow Inc.> Pierre Moulon // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "pairgraphicsitem.h" #include <QtWidgets> PairGraphicsItem::PairGraphicsItem ( const QColor &color, unsigned int x, unsigned int y, unsigned int matches_count ) : color(color), x(x), y(y), matches_count(matches_count) { setFlags(ItemIsSelectable); setAcceptHoverEvents(true); } QRectF PairGraphicsItem::boundingRect() const { return QRectF(0, 0, 100, 100); } QPainterPath PairGraphicsItem::shape() const { QPainterPath path; path.addRect(boundingRect()); return path; } void PairGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); QColor fillColor = (option->state & QStyle::State_Selected) ? color.dark(150) : color; if (option->state & QStyle::State_MouseOver) fillColor = fillColor.light(125); const qreal lod = option->levelOfDetailFromTransform(painter->worldTransform()); if (lod < 0.5) { painter->fillRect(QRectF(0, 0, 100, 100), fillColor); return; } else { const QBrush b = painter->brush(); painter->setBrush(QBrush(fillColor.dark(option->state & (QStyle::State_Sunken ? 120 : 100)))); painter->drawRect(QRect(0, 0, 100, 100)); painter->setBrush(b); // Draw text (information about the camera pair) if (lod < 2) { QFont font("Times", 10); font.setStyleStrategy(QFont::ForceOutline); painter->setFont(font); painter->save(); painter->scale(1.2, 1.2); painter->drawText(10, 20, QString("%1").arg(x)); painter->drawText(10, 60, QString("%1").arg(y)); painter->restore(); } else // (lod >= 2) { QFont font("Times", 10); font.setStyleStrategy(QFont::ForceOutline); painter->setFont(font); painter->save(); painter->scale(0.8, 0.8); painter->drawText(10, 20, QString("Pair: %1; %2").arg(x).arg(y)); painter->drawText(10, 60, QString("#Matches: %1").arg(matches_count)); painter->restore(); } } }
2,345
C++
.cpp
75
27.08
104
0.668587
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,791
mainwindow.cpp
openMVG_openMVG/src/software/ui/SfM/adjacency_matrix_viewer/mainwindow.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 <Zillow Inc.> Pierre Moulon // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "pairgraphicsitem.h" #include "mainwindow.h" #include "mainframe.h" #include "openMVG/matching/indMatch.hpp" #include "openMVG/matching/indMatch_utils.hpp" #include <QHBoxLayout> #include <QSplitter> #include <QtWidgets> MainWindow::MainWindow(QWidget *parent) : QWidget(parent) { view = new MainFrame("Pairwise matches viewer", doc); QMenuBar * menu_bar = new QMenuBar; QMenu * fileMenu = new QMenu(tr("&File")); menu_bar->addMenu(fileMenu); QAction * openAct = new QAction(tr("&Open..."), this); openAct->setShortcuts(QKeySequence::Open); openAct->setStatusTip(tr("Open an existing project")); connect(openAct, &QAction::triggered, this, &MainWindow::open); fileMenu->addAction(openAct); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(menu_bar); layout->addWidget(view); setLayout(layout); setWindowTitle(tr("Pairwise matches viewer")); } void MainWindow::open() { const QString sfm_data_fileName = QFileDialog::getOpenFileName( this, tr("Choose a sfm_data project file"), QString::null, tr("sfm_data files (*.json *.xml *.bin)")); if (sfm_data_fileName.isEmpty()) return; const std::string m_sfm_data_filename = sfm_data_fileName.toStdString(); const QString matches_fileName = QFileDialog::getOpenFileName( this, tr("Choose a matches.X file"), QFileInfo(sfm_data_fileName).path(), tr("matches files (*.bin *.txt)")); if (matches_fileName.isEmpty()) return; const std::string m_matches_data_filename = matches_fileName.toStdString(); populateScene(m_sfm_data_filename, QFileInfo(sfm_data_fileName).path().toStdString(), m_matches_data_filename); view->view()->setScene(scene); emit view->resetView(); } void MainWindow::populateScene ( const std::string & sSfM_Data_Filename, const std::string & sMatchesDir, const std::string & sMatchFile ) { scene = new QGraphicsScene(this); using namespace openMVG; using namespace openMVG::features; using namespace openMVG::matching; using namespace openMVG::sfm; if (!Load(doc.sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS))) { std::cerr << std::endl << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl; return; } //--------------------------------------- // Load SfM Scene regions //--------------------------------------- // Init the regions_type used for this scene from the image describer file const std::string sImage_describer = stlplus::create_filespec(sMatchesDir, "image_describer", "json"); std::unique_ptr<Regions> regions_type = Init_region_type_from_file(sImage_describer); if (!regions_type) { std::cerr << "Invalid: " << sImage_describer << " regions type file." << std::endl; return; } // Read the features doc.feats_provider = std::make_shared<Features_Provider>(); if (!doc.feats_provider->load(doc.sfm_data, sMatchesDir, regions_type)) { std::cerr << std::endl << "Invalid features." << std::endl; return; } // Read the matches doc.matches_provider = std::make_shared<Matches_Provider>(); if (!doc.matches_provider->load(doc.sfm_data, sMatchFile)) { std::cerr << "\nInvalid matches file." << std::endl; return; } std::cout << "Read #Pair: " << doc.matches_provider->getPairs().size() << std::endl; const Pair_Set pairs = doc.matches_provider->getPairs(); for (const auto & pair_iter : pairs) { const auto I = pair_iter.first, J = pair_iter.second; const QColor color(0, 0, 255, 127); QGraphicsItem *item = new PairGraphicsItem( color, I , J, doc.matches_provider->pairWise_matches_.at(pair_iter).size()); item->setPos( QPointF( J * item->boundingRect().width() * 1.1, I * item->boundingRect().height() * 1.1)); scene->addItem(item); } }
4,216
C++
.cpp
118
32.025424
77
0.677879
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,792
mainframe.cpp
openMVG_openMVG/src/software/ui/SfM/adjacency_matrix_viewer/mainframe.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 <Zillow Inc.> Pierre Moulon // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "mainframe.h" #include "pairgraphicsitem.h" #include "matchingpairgraphicsview.h" #ifndef QT_NO_OPENGL #include <QtOpenGL> #else #include <QtWidgets> #endif #include <QSvgWidget> QGraphicsView *MainFrame::view() const { return static_cast<QGraphicsView *>(matching_pair_view); } MainFrame::MainFrame(const QString &name, const Document & doc, QWidget *parent) : QFrame(parent), doc(doc) { setFrameStyle(Sunken | StyledPanel); matching_pair_view = new MatchingPairGraphicsView(this, doc); matching_pair_view->setRenderHint(QPainter::Antialiasing, false); matching_pair_view->setDragMode(QGraphicsView::RubberBandDrag); matching_pair_view->setOptimizationFlags(QGraphicsView::DontSavePainterState); matching_pair_view->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate); matching_pair_view->setTransformationAnchor(QGraphicsView::AnchorUnderMouse); // configure the icon size const int size = style()->pixelMetric(QStyle::PM_ToolBarIconSize); const QSize iconSize(size, size); QToolButton *zoom_in_icon = new QToolButton; zoom_in_icon->setText(tr("-")); zoom_in_icon->setIconSize(iconSize); QToolButton *zoom_out_icon = new QToolButton; zoom_out_icon->setText(tr("+")); zoom_out_icon->setIconSize(iconSize); zoom_slider = new QSlider; zoom_slider->setMinimum(-500); zoom_slider->setMaximum(500); zoom_slider->setValue(0); zoom_slider->setTickPosition(QSlider::TicksRight); // Zoom slider layout QVBoxLayout *zoom_slider_layout = new QVBoxLayout; zoom_slider_layout->addWidget(zoom_in_icon); zoom_slider_layout->addWidget(zoom_slider); zoom_slider_layout->addWidget(zoom_out_icon); reset_button = new QToolButton; reset_button->setText(tr("0")); reset_button->setEnabled(false); // Label layout QHBoxLayout *label_layout = new QHBoxLayout; QLabel *label = new QLabel(name); QLabel *label2 = new QLabel(tr("Pointer Mode")); select_mode_button = new QToolButton; select_mode_button->setText(tr("Select")); select_mode_button->setCheckable(true); select_mode_button->setChecked(true); QToolButton *drag_mode_button = new QToolButton; drag_mode_button->setText(tr("Drag")); drag_mode_button->setCheckable(true); drag_mode_button->setChecked(false); antialias_button = new QToolButton; antialias_button->setText(tr("Antialiasing")); antialias_button->setCheckable(true); antialias_button->setChecked(false); opengl_button = new QToolButton; opengl_button->setText(tr("OpenGL")); opengl_button->setCheckable(true); #ifndef QT_NO_OPENGL opengl_button->setEnabled(QGLFormat::hasOpenGL()); #else opengl_button->setEnabled(false); #endif // // Build the window layout // QButtonGroup *pointer_mode_group = new QButtonGroup(this); pointer_mode_group->setExclusive(true); pointer_mode_group->addButton(select_mode_button); pointer_mode_group->addButton(drag_mode_button); label_layout->addWidget(label); label_layout->addStretch(); label_layout->addWidget(label2); label_layout->addWidget(select_mode_button); label_layout->addWidget(drag_mode_button); label_layout->addStretch(); label_layout->addWidget(antialias_button); label_layout->addWidget(opengl_button); QGridLayout *top_layout = new QGridLayout; top_layout->addLayout(label_layout, 0, 0); top_layout->addWidget(matching_pair_view, 1, 0); top_layout->addLayout(zoom_slider_layout, 1, 1); top_layout->addWidget(reset_button, 2, 1); setLayout(top_layout); // // Confiugre connection between SIGNALs and SLOTs // connect(reset_button, SIGNAL(clicked()), this, SLOT(resetView())); connect(zoom_slider, SIGNAL(valueChanged(int)), this, SLOT(setupMatrix())); connect(matching_pair_view->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(setResetButtonEnabled())); connect(matching_pair_view->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(setResetButtonEnabled())); connect(select_mode_button, SIGNAL(toggled(bool)), this, SLOT(togglePointerMode())); connect(drag_mode_button, SIGNAL(toggled(bool)), this, SLOT(togglePointerMode())); connect(antialias_button, SIGNAL(toggled(bool)), this, SLOT(toggleAntialiasing())); connect(opengl_button, SIGNAL(toggled(bool)), this, SLOT(toggleOpenGL())); connect(zoom_in_icon, SIGNAL(clicked()), this, SLOT(zoomIn())); connect(zoom_out_icon, SIGNAL(clicked()), this, SLOT(zoomOut())); setupMatrix(); } void MainFrame::resetView() { zoom_slider->setValue(0); matching_pair_view->ensureVisible(QRectF(0, 0, 0, 0)); matching_pair_view->fitInView( matching_pair_view->scene()->itemsBoundingRect(), Qt::KeepAspectRatio); reset_button->setEnabled(false); } void MainFrame::setResetButtonEnabled() { reset_button->setEnabled(true); } void MainFrame::setupMatrix() { const qreal scale = qPow(qreal(2), (zoom_slider->value() - 250) / qreal(50)); QMatrix matrix; matrix.scale(scale, scale); matching_pair_view->setMatrix(matrix); setResetButtonEnabled(); } void MainFrame::togglePointerMode() { matching_pair_view->setDragMode(select_mode_button->isChecked() ? QGraphicsView::RubberBandDrag : QGraphicsView::ScrollHandDrag); matching_pair_view->setInteractive(select_mode_button->isChecked()); } void MainFrame::toggleOpenGL() { #ifndef QT_NO_OPENGL matching_pair_view->setViewport( opengl_button->isChecked() ? new QGLWidget(QGLFormat(QGL::SampleBuffers)) : new QWidget); #endif } void MainFrame::toggleAntialiasing() { matching_pair_view->setRenderHint(QPainter::Antialiasing, antialias_button->isChecked()); } void MainFrame::zoomIn(int level) { zoom_slider->setValue(zoom_slider->value() + level); } void MainFrame::zoomOut(int level) { zoom_slider->setValue(zoom_slider->value() - level); }
6,179
C++
.cpp
161
35.217391
91
0.744656
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,793
ControlPoint2DNode.cpp
openMVG_openMVG/src/software/ui/SfM/control_points_registration/ControlPoint2DNode.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "ControlPoint2DNode.hpp" #include <QGraphicsScene> #include <QGraphicsSceneMouseEvent> #include <QPainter> #include <QStyleOption> #include <iostream> ControlPoint2DNode::ControlPoint2DNode ( const QPointF& pos, double & x, double & y, size_t id_control_point ): _id_control_point(id_control_point), _x(x), _y(y) { setFlags(ItemIsMovable | ItemIsSelectable); setFlag(ItemSendsGeometryChanges); setCacheMode(DeviceCoordinateCache); setZValue(1.); setPos(pos); } size_t ControlPoint2DNode::controlPointId() const { return _id_control_point; } QRectF ControlPoint2DNode::boundingRect() const { return QRectF(QPointF(-10,-10),QSize(20,20)); } QPainterPath ControlPoint2DNode::shape() const { QPainterPath path; path.addEllipse(QPointF(0,0),10,10); return path; } void ControlPoint2DNode::paint ( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget ) { QRadialGradient gradient(-3, -3, 10); if (isSelected()) { gradient.setCenter(3, 3); gradient.setFocalPoint(3, 3); gradient.setColorAt(1, QColor(Qt::yellow).light(120)); gradient.setColorAt(0, QColor(Qt::darkYellow).light(120)); } else { gradient.setColorAt(0, Qt::yellow); gradient.setColorAt(1, Qt::darkYellow); } painter->setBrush(gradient); painter->setPen(QPen(Qt::black, 0)); painter->drawEllipse(QPointF(0,0),10,10); // Or just draw a cross ? //painter->setPen(QPen(Qt::black, 1)); //painter->drawLine(10, 10, -10, -10); //painter->drawLine(10, -10, -10, 10); // Paint the index of the control_point // adapt the font size to fit the GCP id to the bounding box of the ellipse const QRectF node_rect(QPointF(-8,-8),QSize(18,18)); const QString s_node_id = QString::number(_id_control_point); const float factor = node_rect.width() / painter->fontMetrics().width(s_node_id); painter->setPen(QPen(Qt::black, 5)); if (factor < 1) { QFont f = painter->font(); f.setPointSizeF(f.pointSizeF()*factor); painter->setFont(f); } painter->drawText(node_rect, Qt::AlignCenter, s_node_id); } QVariant ControlPoint2DNode::itemChange ( GraphicsItemChange change, const QVariant &value ) { const QVariant variant = QGraphicsItem::itemChange(change, value); _x = scenePos().x(); _y = scenePos().y(); return variant; } void ControlPoint2DNode::mousePressEvent ( QGraphicsSceneMouseEvent *event ) { update(); QGraphicsItem::mousePressEvent(event); } void ControlPoint2DNode::mouseReleaseEvent ( QGraphicsSceneMouseEvent *event ) { update(); QGraphicsItem::mouseReleaseEvent(event); }
2,926
C++
.cpp
108
24.62963
83
0.732525
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,795
MainWindow.cpp
openMVG_openMVG/src/software/ui/SfM/control_points_registration/MainWindow.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "MainWindow.hpp" #include <QFileDialog> #include <QGridLayout> #include <QMenuBar> #include <QDebug> #include <QMenu> #include <QMessageBox> #include <QSplitter> #include <QStatusBar> #include <QtGui> #include <QWidget> #include <algorithm> #include <clocale> #include "ControlPoint2DNode.hpp" #include "ControlPointTableView.hpp" #include "openMVG/cameras/Camera_Intrinsics.hpp" #include "openMVG/multiview/triangulation_nview.hpp" #include "openMVG/sfm/sfm_data_triangulation.hpp" #include "openMVG/geometry/rigid_transformation3D_srt.hpp" #include "openMVG/geometry/Similarity3.hpp" #include "openMVG/sfm/sfm_data_BA_ceres.hpp" #include "openMVG/sfm/sfm_data_transform.hpp" #include "openMVG/stl/stl.hpp" using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::sfm; void MainWindow::removeAllControlPoints() { m_doc._sfm_data.control_points = Landmarks(); doubleClickImageList(); } void MainWindow::help() { QMessageBox::about(this, tr("About"), tr( "This application allow to perform a rigid registration of a SfM scene to know GCP (Ground Control Points)<br>" "<b>Important:</b><br>" "Each GCP must have a unique numbered ID.<br>" "<b>1-</b> Add GCP image observations:<br>" " - double-click on one image on the left (in which you want add a GCP observation)<br>" " - click on the displayed image on the right, and choose your ID and move your GCP observation to the right place.<br>" " - to move a GCP observation, click on it and move your mouse with left-click pressed.<br>" "<b>2-</b> Edit GCP 3D positions:<br>" " - Go to Control Point Edition menu (Ctrl+E) and edit the 3D position<br>" "<b>3-</b> Registration:<br>" "- Go to Control Point registration menu (Ctrl+R) and save your scene.<br>" "<br>" "Tip:<br>" "CTRL+WHEEL: Image zoom in/out" )); } void MainWindow::doubleClickImageList() { const QModelIndex modelIndex = m_treeView_Images->currentIndex(); const QModelIndex res = modelIndex.sibling ( modelIndex.row(), 0 ); const QString current_string_clicked = res.data().toString(); std::istringstream is(current_string_clicked.toStdString()); size_t id; is >> id; if (m_doc._sfm_data.GetViews().count(id) == 1) { const View * view = m_doc._sfm_data.GetViews().at(id).get(); const std::string sView = stlplus::create_filespec(m_doc._sfm_data.s_root_path, view->s_Img_path); m_widget->addImage(QString::fromStdString(sView), 0.f, 0.f, true); m_widget->setCurrentViewId(view->id_view); setWindowTitle(QString("Control_point_editor: " + QString::fromStdString(sView))); // Display control points information related to this view for (Landmarks::iterator iterL = m_doc._sfm_data.control_points.begin(); iterL != this->m_doc._sfm_data.control_points.end(); ++iterL) { Landmark & landmark = iterL->second; Observations & obs = landmark.obs; if (obs.count(view->id_view) != 0) { // Create a graphical instance that points directly to the control point 2d observation // It will allow dynamic update of the control_point observation when the user will move the Node Vec2 & ref = obs[view->id_view].x; const size_t index = iterL->first; m_widget->addNode(new ControlPoint2DNode(QPointF(ref(0), ref(1)), ref(0), ref(1), index)); } } } } void MainWindow::saveProject() { const QString dir = QString::fromStdString(stlplus::folder_part(m_sfm_data_filename)); const QString sfm_data_filename = QFileDialog::getSaveFileName(this, tr("Choose a sfm_data file (sfm_data.json)"), dir, tr("sfm_data (*.json *.xml *.bin)")); if (sfm_data_filename.isEmpty()) return; std::setlocale(LC_ALL, "C"); if (!m_doc.saveData(sfm_data_filename.toStdString())) { QMessageBox msgBox; msgBox.setText("Cannot save the sfm_data file."); msgBox.exec(); } } void MainWindow::openProject() { const QString sfm_data_fileName = QFileDialog::getOpenFileName(this, tr("Choose a sfm_data project file"), QString::null, tr("sfm_data (*.json *.xml *.bin)")); if (sfm_data_fileName.isEmpty()) return; m_sfm_data_filename = sfm_data_fileName.toStdString(); if (m_doc.loadData(sfm_data_fileName.toStdString())) { //Add image names in the QT tree view { QStandardItemModel * model = new QStandardItemModel(0,1, this); model->setHeaderData(0, Qt::Horizontal, QObject::tr("Views")); m_treeView_Images->setModel(model); std::vector<IndexT> view_ids; view_ids.reserve(m_doc._sfm_data.GetViews().size()); std::transform(m_doc._sfm_data.GetViews().begin(), m_doc._sfm_data.GetViews().end(), std::back_inserter(view_ids), stl::RetrieveKey()); std::sort(view_ids.begin(), view_ids.end()); // Add view in reverse order to have them ordered by ID for (std::vector<IndexT>::const_reverse_iterator iter = view_ids.rbegin(); iter != view_ids.rend(); ++iter) { Views::const_iterator iterV = m_doc._sfm_data.GetViews().find(*iter); const View * view = iterV->second.get(); if (m_doc._sfm_data.IsPoseAndIntrinsicDefined(view)) { std::ostringstream os; os << view->id_view << " " << view->s_Img_path; model->insertRow(0); model->setData(model->index(0, 0), QString::fromStdString(os.str())); } } } } else { QMessageBox msgBox; msgBox.setText("Cannot open the provided sfm_data file."); msgBox.exec(); } } void MainWindow::editControlPoints() { // Graphical widget to configure the control point position if (!m_doc._sfm_data.control_points.empty()) { using namespace control_point_GUI; ControlPointTableView control_point_editor(&m_doc._sfm_data, this); control_point_editor.exec(); Landmarks control_points_cpy = m_doc._sfm_data.control_points; control_point_editor.updateControlPoints(control_points_cpy); m_doc._sfm_data.control_points = control_points_cpy; } else { QMessageBox msgBox; msgBox.setText("No defined control points."); msgBox.exec(); return; } } // Find pattern occurences and replace it by a new one static std::string string_pattern_replace ( std::string subject, const std::string& search, const std::string& replace ) { size_t pos = 0; while ((pos = subject.find(search, pos)) != std::string::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } return subject; } void MainWindow::registerProject() { if (m_doc._sfm_data.control_points.size() < 3) { QMessageBox msgBox; msgBox.setText("At least 3 control points are required."); msgBox.exec(); return; } // Assert that control points can be triangulated for (Landmarks::const_iterator iterL = m_doc._sfm_data.control_points.begin(); iterL != m_doc._sfm_data.control_points.end(); ++iterL) { if (iterL->second.obs.size() < 2) { QMessageBox msgBox; msgBox.setText("Each control point must be defined in at least 2 pictures."); msgBox.exec(); return; } } //--- // registration (coarse): // - compute the 3D points corresponding to the control point observation for the SfM scene // - compute a coarse registration between the controls points & the triangulated point // - transform the scene according the found transformation //--- std::map<IndexT, Vec3> map_control_points, map_triangulated; std::map<IndexT, double> map_triangulation_errors; for (const auto & control_point_it : m_doc._sfm_data.control_points) { const Landmark & landmark = control_point_it.second; //Triangulate the observations: const Observations & obs = landmark.obs; std::vector<Vec3> bearing; std::vector<Mat34> poses; bearing.reserve(obs.size()); poses.reserve(obs.size()); for (const auto & obs_it : obs) { const View * view = m_doc._sfm_data.views.at(obs_it.first).get(); if (!m_doc._sfm_data.IsPoseAndIntrinsicDefined(view)) continue; const openMVG::cameras::IntrinsicBase * cam = m_doc._sfm_data.GetIntrinsics().at(view->id_intrinsic).get(); const openMVG::geometry::Pose3 pose = m_doc._sfm_data.GetPoseOrDie(view); const Vec2 pt = obs_it.second.x; bearing.emplace_back((*cam)(cam->get_ud_pixel(pt))); poses.emplace_back(pose.asMatrix()); } const Eigen::Map<const Mat3X> bearing_matrix(bearing[0].data(), 3, bearing.size()); Vec4 Xhomogeneous; if (!TriangulateNViewAlgebraic(bearing_matrix, poses, &Xhomogeneous)) { std::cout << "Invalid triangulation" << std::endl; return; } const Vec3 X = Xhomogeneous.hnormalized(); // Test validity of the hypothesis (front of the cameras): bool bCheirality = true; int i(0); double reprojection_error_sum(0.0); for (const auto & obs_it : obs) { const View * view = m_doc._sfm_data.views.at(obs_it.first).get(); if (!m_doc._sfm_data.IsPoseAndIntrinsicDefined(view)) continue; const Pose3 pose = m_doc._sfm_data.GetPoseOrDie(view); bCheirality &= CheiralityTest(bearing[i], pose, X); const openMVG::cameras::IntrinsicBase * cam = m_doc._sfm_data.GetIntrinsics().at(view->id_intrinsic).get(); const Vec2 pt = obs_it.second.x; const Vec2 residual = cam->residual(pose(X), pt); reprojection_error_sum += residual.norm(); ++i; } if (bCheirality) // Keep the point only if it has a positive depth { map_triangulated[control_point_it.first] = X; map_control_points[control_point_it.first] = landmark.X; map_triangulation_errors[control_point_it.first] = reprojection_error_sum/(double)bearing.size(); } else { std::cout << "Control Point cannot be triangulated (not in front of the cameras)" << std::endl; return; } } if (map_control_points.size() < 3) { QMessageBox msgBox; msgBox.setText("Insufficient number of triangulated control points."); msgBox.exec(); return; } // compute the similarity { // data conversion to appropriate container Mat x1(3, map_control_points.size()), x2(3, map_control_points.size()); IndexT id_col = 0; for (const auto & cp : map_control_points) { x1.col(id_col) = map_triangulated[cp.first]; x2.col(id_col) = cp.second; ++id_col; } std::cout << "Control points observation triangulations:\n" << x1 << std::endl << std::endl << "Control points coords:\n" << x2 << std::endl << std::endl; Vec3 t; Mat3 R; double S; if (openMVG::geometry::FindRTS(x1, x2, &S, &t, &R)) { openMVG::geometry::Refine_RTS(x1,x2,&S,&t,&R); std::cout << "Found transform:\n" << " scale: " << S << "\n" << " rotation:\n" << R << "\n" << " translation: "<< t.transpose() << std::endl; //-- // Apply the found transformation as a 3D Similarity transformation matrix // S * R * X + t //-- const openMVG::geometry::Similarity3 sim(geometry::Pose3(R, -R.transpose() * t/S), S); openMVG::sfm::ApplySimilarity(sim, m_doc._sfm_data); // Display some statistics: std::stringstream os; for (Landmarks::const_iterator iterL = m_doc._sfm_data.control_points.begin(); iterL != m_doc._sfm_data.control_points.end(); ++iterL) { const IndexT CPIndex = iterL->first; // If the control point has not been used, continue... if (map_triangulation_errors.find(CPIndex) == map_triangulation_errors.end()) continue; os << "CP index: " << CPIndex << "\n" << "CP triangulation error: " << map_triangulation_errors[CPIndex] << " pixel(s)\n" << "CP registration error: " << (sim(map_triangulated[CPIndex]) - map_control_points[CPIndex]).norm() << " user unit(s)"<< "\n\n"; } std::cout << os.str(); QMessageBox msgBox; msgBox.setText(QString::fromStdString(string_pattern_replace(os.str(), "\n", "<br>"))); msgBox.exec(); } else { QMessageBox msgBox; msgBox.setText("Registration failed. Please check your Control Points coordinates."); msgBox.exec(); } } //--- // Bundle adjustment with GCP //--- { using namespace openMVG::sfm; Bundle_Adjustment_Ceres::BA_Ceres_options options; Bundle_Adjustment_Ceres bundle_adjustment_obj(options); Control_Point_Parameter control_point_opt(20.0, true); if (!bundle_adjustment_obj.Adjust(m_doc._sfm_data, Optimize_Options ( cameras::Intrinsic_Parameter_Type::NONE, // Keep intrinsic constant Extrinsic_Parameter_Type::ADJUST_ALL, // Adjust camera motion Structure_Parameter_Type::ADJUST_ALL, // Adjust structure control_point_opt // Use GCP and weight more their observation residuals ) ) ) { QMessageBox msgBox; msgBox.setText("BA with GCP failed."); msgBox.exec(); } } } MainWindow::MainWindow ( QWidget * parent ): QMainWindow() { createPanel(); createActions(); createMenus(); createConnections(); setWindowTitle(tr("Control_point_editor")); QMainWindow::statusBar()->showMessage("Welcome in Control_point_editor GUI."); resize(640, 480); } void MainWindow::createPanel() { QSplitter *splitter = new QSplitter; //-- Create left panel m_tabWidget = new QTabWidget; //-- Create right panel m_widget = new control_point_GUI::GraphicsView(m_doc, this); splitter->addWidget(m_tabWidget); splitter->addWidget(m_widget); splitter->setStretchFactor(0, 0); splitter->setStretchFactor(1, 1); setCentralWidget(splitter); //-- Add tab inside the m_tabWidget m_tab_1 = new QWidget; m_tab_1->setObjectName(QString::fromUtf8("m_tab_1")); m_tabWidget->addTab(m_tab_1, QString()); m_tabWidget->setTabText(m_tabWidget->indexOf(m_tab_1), "ImageList"); //-- Configure tab widgets m_treeView_Images = new QTreeView(m_tab_1); m_treeView_Images->setRootIsDecorated(false); m_treeView_Images->setEditTriggers(QAbstractItemView::NoEditTriggers); m_treeView_Images->setObjectName(QString::fromUtf8("m_treeView_Images")); m_treeView_Images->setSortingEnabled(true); QGridLayout * gridLayout1 = new QGridLayout(m_tab_1); gridLayout1->addWidget(m_treeView_Images, 0, 0, 1, 1); } void MainWindow::createMenus() { m_menuFile = new QMenu(tr("&File"),this); m_menuFile->setObjectName(QString::fromUtf8("m_menuFile")); menuBar()->addMenu(m_menuFile); m_menuFile->addAction(m_open_action); m_menuFile->setObjectName(QString::fromUtf8("m_menuSave")); m_menuFile->addAction(m_save_action); QMenu * m_menuEditCp= new QMenu(tr("Control Point &Edition"),this); m_menuEditCp->setObjectName(QString::fromUtf8("m_menuCPEdition")); m_menuFile->addAction(m_edit_cp_action); QMenu * m_menuRegister = new QMenu(tr("Control Point &Registration"),this); m_menuRegister->setObjectName(QString::fromUtf8("m_menuRegister")); m_menuFile->addAction(m_register_action); QMenu * m_menuDelete = new QMenu(tr("&Delete All Control Point"),this); m_menuDelete->setObjectName(QString::fromUtf8("m_menuDelete")); m_menuFile->addAction(m_delete_control_point_action); m_menuHelp = new QMenu(tr("&Help"),this); m_menuHelp->setObjectName(QString::fromUtf8("m_menuHelp")); menuBar()->addMenu(m_menuHelp); m_menuHelp->addAction(m_help_action); } void MainWindow::createActions() { m_open_action = new QAction(tr("&Open Project..."), this); m_open_action->setShortcut(tr("Ctrl+O")); connect(m_open_action, SIGNAL(triggered()), this, SLOT(openProject())); m_save_action = new QAction(tr("&Save Project..."), this); m_save_action->setShortcut(tr("Ctrl+S")); connect(m_save_action, SIGNAL(triggered()), this, SLOT(saveProject())); m_register_action = new QAction(tr("Control Point &Registration..."), this); m_register_action->setShortcut(tr("Ctrl+R")); connect(m_register_action, SIGNAL(triggered()), this, SLOT(registerProject())); m_edit_cp_action = new QAction(tr("Control Point &Edition..."), this); m_edit_cp_action->setShortcut(tr("Ctrl+E")); connect(m_edit_cp_action, SIGNAL(triggered()), this, SLOT(editControlPoints())); m_help_action = new QAction(tr("&Help"), this); m_help_action->setShortcut(tr("Ctrl+H")); connect(m_help_action, SIGNAL(triggered()), this, SLOT(help())); m_delete_control_point_action = new QAction(tr("&Delete All Control Point..."), this); m_delete_control_point_action->setShortcut(tr("Ctrl+D")); connect(m_delete_control_point_action, SIGNAL(triggered()), this, SLOT(removeAllControlPoints())); } void MainWindow::createConnections() { connect (m_treeView_Images ,SIGNAL(activated(const QModelIndex &)) ,this ,SLOT(doubleClickImageList()) ); }
17,261
C++
.cpp
454
33.444934
123
0.677161
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,797
GraphicsView.cpp
openMVG_openMVG/src/software/ui/SfM/control_points_registration/GraphicsView.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "GraphicsView.hpp" #include "ControlPoint2DNode.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" // Qt4 headers #include <QtGui> #include <QGraphicsScene> #include <QGraphicsView> #include <QGraphicsLineItem> #include <QGraphicsItem> #include <QAction> #include <QMessageBox> #include <memory> #include <QPen> #include <QInputDialog> #include <iostream> #include <fstream> #include <iterator> namespace control_point_GUI { using namespace openMVG; using namespace openMVG::sfm; // ========================================================================= // Public methods // ========================================================================= GraphicsView::GraphicsView(Document & doc, QWidget * parent) : QGraphicsView(parent), scene(new QGraphicsScene), _doc(doc), _current_view_id(UndefinedIndexT) { setScene(scene); // The OpenGL rendering does not seem to work with too big images. //setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); setBackgroundRole(QPalette::Dark); setAlignment(Qt::AlignCenter); setCacheMode(QGraphicsView::CacheBackground); setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); setTransformationAnchor(QGraphicsView::AnchorUnderMouse); setMouseTracking(true); createActions(); resize(800, 600); } void GraphicsView::zoomIn() { scale(1.25, 1.25); update(); } void GraphicsView::zoomOut() { scale(0.8, .8); update(); } void GraphicsView::normalSize() { resetTransform(); update(); } void GraphicsView::removeControlPoint() { auto items = scene->selectedItems(); foreach (auto item, items) { auto cp = dynamic_cast<ControlPoint2DNode *>(item); if (!cp) continue; auto i = _doc._sfm_data.control_points.find(cp->controlPointId()); if (i != _doc._sfm_data.control_points.end()) { Landmark & landmark = i->second; landmark.obs.erase(_current_view_id); if (landmark.obs.empty()) _doc._sfm_data.control_points.erase(i); } delete cp; } } // ========================================================================= // Protected methods // ========================================================================= void GraphicsView::drawBackground(QPainter *painter, const QRectF &rect) { } void GraphicsView::mousePressEvent (QMouseEvent* e ) { QGraphicsView::mousePressEvent(e); if (e->isAccepted()) return; // QGraphicsView handled this event if (_doc._sfm_data.GetViews().empty() || e->button()!=Qt::LeftButton) { return; } e->accept(); // We handled this event const QPointF pos = this->mapToScene(e->pos()); int index = -1; QInputDialog input; input.setInputMode(QInputDialog::IntInput); input.setWindowTitle(""); input.setLabelText("Control point ID"); input.setIntRange(0, 9999); input.setIntValue(0); input.setIntStep(1); if (input.exec() == QDialog::Accepted) { index = input.intValue(); } if (index != -1) { // Try to setup a new landmark: Landmark & landmark = this->_doc._sfm_data.control_points[index]; if (landmark.obs.count(_current_view_id) == 0) { landmark.obs[_current_view_id] = Observation(Vec2(pos.x(), pos.y()), 0); // Create a graphical instance that points directly to the control point observation Vec2 & ref = landmark.obs[_current_view_id].x; this->addNode(new ControlPoint2DNode(pos, ref(0), ref(1), index)); } else { QMessageBox msgBox; msgBox.setText("There is already an observation linked to the depicted control_point in this image. Please select a new Id."); msgBox.exec(); // If the control point was not existing, clear it if (landmark.obs.empty()) this->_doc._sfm_data.control_points.erase(this->_doc._sfm_data.control_points.find(index)); } } } void GraphicsView::wheelEvent ( QWheelEvent * e) { if (e->modifiers().testFlag(Qt::ControlModifier)) // zoom only when CTRL key is pressed { const int numSteps = e->delta() / 15 / 8; if (numSteps == 0) { e->ignore(); return; } if (numSteps > 0) zoomIn(); else zoomOut(); e->accept(); } else { QGraphicsView::wheelEvent(e); } } void GraphicsView::zoom(qreal factor, QPointF centerPoint) { scale(factor, factor); //centerOn(centerPoint); } // ========================================================================= // Private methods // ========================================================================= void GraphicsView::createActions() { zoomInAct = new QAction(tr("Zoom &In (25%)"), this); zoomInAct->setShortcut(tr("Ctrl++")); zoomInAct->setEnabled(false); connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn())); addAction(zoomInAct); zoomOutAct = new QAction(tr("Zoom &Out (25%)"), this); zoomOutAct->setShortcut(tr("Ctrl+-")); zoomOutAct->setEnabled(false); connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut())); addAction(zoomOutAct); normalSizeAct = new QAction(tr("&Normal Size"), this); normalSizeAct->setShortcut(tr("Ctrl+1")); normalSizeAct->setEnabled(false); connect(normalSizeAct, SIGNAL(triggered()), this, SLOT(normalSize())); addAction(normalSizeAct); removeControlPointAct = new QAction(tr("&Remove Control Point"), this); removeControlPointAct->setShortcut(tr("Del")); removeControlPointAct->setEnabled(false); connect(removeControlPointAct, SIGNAL(triggered()), this, SLOT(removeControlPoint())); addAction(removeControlPointAct); } void GraphicsView::addImage(const QString & qs_filename, float xpos, float ypos, bool bClear) { if (bClear) { scene->clear(); } QGraphicsPixmapItem * image = new QGraphicsPixmapItem; image->setTransformationMode(Qt::FastTransformation); scene->addItem(image); QPixmap pixmap(qs_filename); if (pixmap.isNull()) { QMessageBox::information(this, QString::null, tr("Cannot load QPixmap %1.").arg(qs_filename)); return; } else { const QPointF offset = QPointF(xpos, ypos); image->setPixmap(pixmap); image->setPos(offset); zoomInAct->setEnabled(true); zoomOutAct->setEnabled(true); normalSizeAct->setEnabled(true); removeControlPointAct->setEnabled(true); const QFileInfo fi(qs_filename); const QString name = fi.fileName(); qDebug() << "Current viewed image: " << name; } } void GraphicsView::addNode(QGraphicsItem* it) { scene->addItem(it); } } // namespace control_point_GUI
7,175
C++
.cpp
206
29.737864
134
0.626769
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,798
openMVG_main_openMVG2WebGL.cpp
openMVG_openMVG/src/software/SfMWebGLViewer/openMVG_main_openMVG2WebGL.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 Romuald Perrot. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/cameras/Camera_Pinhole.hpp" #include "openMVG/geometry/pose3.hpp" #include "openMVG/geometry/frustum.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/sfm/sfm_data_colorization.hpp" #include "openMVG/stl/stl.hpp" #include "openMVG/system/loggerprogress.hpp" #include "config.h" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <iostream> #include <fstream> using namespace openMVG; using namespace openMVG::sfm; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::cameras; /** * @brief Compute normal using the mean of the direction for each points * @param sfm_data Input scene data * @param vec_nor A vector of normal for each point (in same order as ColorizeTrack output) */ void ComputeNormals( const SfM_Data & sfm_data , std::vector<Vec3> & vec_nor ) { vec_nor.resize( sfm_data.GetLandmarks().size() ); IndexT cpt = 0; for (Landmarks::const_iterator it = sfm_data.GetLandmarks().begin(); it != sfm_data.GetLandmarks().end(); ++it, ++cpt) { // Set it's normal to 0,0,0 vec_nor[ cpt ] = Vec3(0,0,0); const Landmark & landmark = it->second; const Observations & obs = landmark.obs; // Sum all rays from all observations for (Observations::const_iterator itOb = obs.begin(); itOb != obs.end(); ++itOb ) { const IndexT viewId = itOb->first; // Compute ray of this obs const Observation & ob = itOb->second; const Vec2 & pos = ob.x; const View * view = sfm_data.GetViews().at(viewId).get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) { continue; } // get it's intrinsic (if available) Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); if (!isPinhole(iterIntrinsic->second->getType())) { continue; } const Pose3 pose = sfm_data.GetPoseOrDie(view); // Force a pinhole ? (TODO : need to work with another type of camera) const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(iterIntrinsic->second.get()); // Compute vector from camera center to the point const Vec3 C = pose.center(); const Mat3 Kinv = cam->K().inverse(); const Mat3 Rt = pose.rotation().transpose(); // TODO : good for educational but really inefficient ! (+C-C) const Vec3 dst = Rt * ( ( Kinv * Vec3( pos.x() , pos.y() , 1.0 ) ) ) + C; const Vec3 n = ( dst - C ).normalized(); vec_nor[ cpt ] += n; } // Mean and normalize vec_nor[ cpt ] = vec_nor[ cpt ].normalized(); } } /** * @brief Export scene data to a file * @param sfm_data Input scene data * @param sOutFile Output file name */ bool ExportSceneData( const SfM_Data & sfm_data, const std::string & sOutFile ) { std::ofstream file( sOutFile ); if ( ! file ) { std::cerr << std::endl; std::cerr << "Could not create : " << sOutFile << std::endl; return false; } std::vector<Vec3> vec_3dPoints, vec_tracksColor , vec_normals; ColorizeTracks(sfm_data, vec_3dPoints, vec_tracksColor); ComputeNormals(sfm_data,vec_normals); // Model points file << "modelPos=[" << std::endl; for (size_t id_point = 0; id_point < vec_3dPoints.size(); ++id_point) { file << vec_3dPoints[id_point](0) << " , " << vec_3dPoints[id_point](1) << " , " << vec_3dPoints[id_point](2); if (id_point +1 != vec_3dPoints.size() ) { file << " , "; } } file << "];" << std::endl; // Model normal file << "modelNor=[" << std::endl; for (size_t id_nor = 0; id_nor < vec_normals.size(); ++id_nor) { file << vec_normals[ id_nor ](0) << " , " << vec_normals[ id_nor ](1) << " , " << vec_normals[ id_nor ](2); if (id_nor + 1 != vec_normals.size() ) { file << " , "; } } file << "];" << std::endl; // Model color file << "modelCol=[" << std::endl; for (size_t id_point = 0; id_point < vec_tracksColor.size(); ++id_point) { file << vec_tracksColor[id_point](0) << " , " << vec_tracksColor[id_point](1) << " , " << vec_tracksColor[id_point](2); if (id_point + 1 != vec_tracksColor.size() ) { file << " , "; } } file << "];" << std::endl; // Camera positions file << "cameraPos=[" << std::endl; for (auto it = sfm_data.GetViews().begin(); it != sfm_data.GetViews().end();) { const View * view = sfm_data.GetViews().at(it->first).get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) { ++it; continue; } // get it's intrinsic (if available) Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); if (!isPinhole(iterIntrinsic->second->getType())) { ++it; continue; } const Pose3 pose = sfm_data.GetPoseOrDie(view); // Force a pinhole ? (TODO : need to work with another type of camera) const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(iterIntrinsic->second.get()); if (cam == nullptr) { ++it; continue; } // Build frustum const Frustum f( cam->w() , cam->h() , cam->K() , pose.rotation() , pose.center() , 0.5 ); const Vec3 pos = f.cones[0]; file << "[" << pos[0] << "," << pos[1] << "," << pos[2] << "]"; if ( ++it != sfm_data.GetViews().end() ) { file << ","; } } file << "];" << std::endl; // Camera image planes file << "cameraImagePlanes=[" << std::endl; for (auto it = sfm_data.GetViews().begin(); it != sfm_data.GetViews().end();) { const View * view = sfm_data.GetViews().at(it->first).get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) { ++it; continue; } // get it's intrinsic (if available) Intrinsics::const_iterator iterIntrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); if (!isPinhole(iterIntrinsic->second->getType())) { ++it; continue; } const Pose3 pose = sfm_data.GetPoseOrDie(view); // Force a pinhole ? (TODO : need to work with another type of camera) const Pinhole_Intrinsic * cam = dynamic_cast<const Pinhole_Intrinsic*>(iterIntrinsic->second.get()); if (cam == nullptr) { ++it; continue; } // Build frustum const Frustum f( cam->w() , cam->h() , cam->K() , pose.rotation() , pose.center() , 0.33 ); const Vec3 & p1 = f.cones[1]; const Vec3 & p2 = f.cones[2]; const Vec3 & p3 = f.cones[3]; const Vec3 & p4 = f.cones[4]; file << "["; file << p1[0] << "," << p1[1] << "," << p1[2] << ","; file << p2[0] << "," << p2[1] << "," << p2[2] << ","; file << p3[0] << "," << p3[1] << "," << p3[2] << ","; file << p4[0] << "," << p4[1] << "," << p4[2] << "]"; if ( ++it != sfm_data.GetViews().end() ) { file << ","; } } file << "];" << std::endl; file.close(); return true; } bool CopyFile( const std::string & inputFolder , const std::string & inputName , const std::string & outputFolder , const std::string & outputSubFolder , const std::string & outputName ) { std::string outputFilename; if (outputSubFolder.length() > 0 ) { outputFilename = stlplus::create_filespec( stlplus::folder_append_separator( outputFolder ) + outputSubFolder , outputName ); } else { outputFilename = stlplus::create_filespec( outputFolder , outputName ); } const std::string inputFilename1 = stlplus::create_filespec( stlplus::folder_append_separator( OPENMVG_SFM_WEBGL_SRC_PATH ) + inputFolder , inputName ); const std::string inputFilename2 = stlplus::create_filespec( stlplus::folder_append_separator( OPENMVG_SFM_WEBGL_INSTALL_SHARED_PATH ) + inputFolder , inputName ); // Prefer Build path std::string usablePath = inputFilename1; if ( ! stlplus::file_exists( inputFilename1 ) ) { usablePath = inputFilename2; } if ( ! stlplus::file_copy( usablePath , outputFilename ) ) { std::cerr << "Error copying " << inputName << " file" << std::endl; return false; } return true; } /** * Stupid template trick to get the size of a static c array */ template < typename T , int N> int StaticArraySize( T (&)[N] ) { return N; } /** * @brief Export a sfm scene to a webgl app * @param sSfM_Data_Filename Filename of the sfm scene * @param sOutDir Output directory * @note If output directory no present, create it * @retval true if everything was correct * @retval false if there was an error */ bool ExportToWebGL( const std::string & sSfM_Data_Filename , const std::string & sOutDir ) { // Load input scene SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(ALL))) { std::cerr << std::endl << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl; return false; } // Check output directory // OUT_DIR / // / common // / style // / model bool bOk = true; if (!stlplus::is_folder(sOutDir)) { stlplus::folder_create(sOutDir); bOk = stlplus::is_folder(sOutDir); } stlplus::folder_create( stlplus::folder_append_separator(sOutDir) + "common" ); stlplus::folder_create( stlplus::folder_append_separator(sOutDir) + "style" ); stlplus::folder_create( stlplus::folder_append_separator(sOutDir) + "model" ); if (! stlplus::is_folder( stlplus::folder_append_separator(sOutDir) + "common") || ! stlplus::is_folder( stlplus::folder_append_separator(sOutDir) + "style") || ! stlplus::is_folder( stlplus::folder_append_separator(sOutDir) + "model" ) ) { bOk = false; } if ( ! bOk ) { std::cerr << "Could not create directory structure : \"" << sOutDir << "\"" << std::endl; return false; } // 1 - Export scene specific data const std::string modelFilename = stlplus::create_filespec( stlplus::folder_append_separator( sOutDir ) + "model" , "model.js" ); std::cerr << "Modelfilename:" << modelFilename << std::endl; ExportSceneData( sfm_data , modelFilename ); const std::string files_to_copy[] = { "common" , "index.html" , sOutDir , "" , "index.html" , // 1 "common" , "style.css" , sOutDir , "style" , "style.css" , // 2 "common" , "main.js" , sOutDir , "common" , "main.js" , // 3 "common" , "quaternion.js" , sOutDir , "common" , "quaternion.js" , // 4 "common" , "dual_quaternion.js" , sOutDir , "common" , "dual_quaternion.js" , // 5 "common" , "common.js" , sOutDir , "common" , "common.js" , // 6 "common" , "matrix4.js" , sOutDir , "common" , "matrix4.js" , // 7 "common" , "matrix3.js" , sOutDir , "common" , "matrix3.js" , // 8 "common" , "plane.js" , sOutDir , "common" , "plane.js" , // 9 "common" , "camera.js" , sOutDir , "common" , "camera.js" , // 10 "common" , "shader.js" , sOutDir , "common" , "shader.js" , // 11 "common" , "trackball.js" , sOutDir , "common" , "trackball.js" , // 12 "common" , "render_context.js" , sOutDir , "common" , "render_context.js" , // 13 "common" , "vector.js" , sOutDir , "common" , "vector.js" , // 14 "common" , "point_cloud.js" , sOutDir , "common" , "point_cloud.js" , // 15 "common" , "camera_gizmo.js" , sOutDir , "common" , "camera_gizmo.js" // 16 }; // Copy the js files for (int id_file = 0; id_file < StaticArraySize( files_to_copy ) / 5; ++id_file) { const std::string & input_folder = files_to_copy[ 5 * id_file ]; const std::string & input_name = files_to_copy[ 5 * id_file + 1 ]; const std::string & output_folder = files_to_copy[ 5 * id_file + 2 ]; const std::string & output_subfolder = files_to_copy[ 5 * id_file + 3 ]; const std::string & output_name = files_to_copy[ 5 * id_file + 4 ]; if ( ! CopyFile( input_folder , input_name , output_folder , output_subfolder , output_name ) ) { return false; } } return true; } int main( int argc , char ** argv ) { // -i sfm_data.bin -o directory CmdLine cmd; std::string sSfM_Data_Filename; std::string sOutDir = ""; cmd.add( make_option('i', sSfM_Data_Filename, "sfmdata") ); cmd.add( make_option('o', sOutDir, "outdir") ); try { if (argc == 1) { throw std::string("Invalid command line parameter."); } cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--sfmdata] filename, the SfM_Data file to convert\n" << "[-o|--outdir path]\n" << std::endl; std::cerr << s << std::endl; exit( EXIT_FAILURE ); } std::cout << "Using : " << std::endl; std::cout << "Input file : " << sSfM_Data_Filename << std::endl; std::cout << "Output dir : " << sOutDir << std::endl; if ( ! ExportToWebGL( sSfM_Data_Filename , sOutDir ) ) { std::cerr << "There was an error during export" << std::endl; exit( EXIT_FAILURE ); } return EXIT_SUCCESS; }
13,472
C++
.cpp
357
33.140056
166
0.610434
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,801
main_benchANN.cpp
openMVG_openMVG/src/software/SfM/main_benchANN.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2019 Romain Janvier, Pierre Moulon // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/sfm/pipelines/sfm_preemptive_regions_provider.hpp" #include "openMVG/sfm/pipelines/sfm_regions_provider.hpp" #include "openMVG/sfm/pipelines/sfm_regions_provider_cache.hpp" #include "openMVG/matching_image_collection/Cascade_Hashing_Matcher_Regions.hpp" #include "openMVG/matching_image_collection/Matcher_Regions.hpp" #include "openMVG/matching_image_collection/Pair_Builder.hpp" #include "openMVG/matching/regions_matcher.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/stl/stl.hpp" #include "openMVG/system/loggerprogress.hpp" #include "openMVG/system/timer.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cstdlib> #include <iostream> #include <memory> #include <string> using namespace openMVG; using namespace matching; using namespace openMVG::matching_image_collection; using namespace openMVG::sfm; struct Counter { struct value_type { template<typename T> value_type(const T&) { } }; void push_back(const value_type&) { ++count; } size_t count = 0; }; template<typename T1, typename T2> size_t intersection_size(const T1& s1, const T2& s2) { Counter c; set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(c)); return c.count; } int main(int argc, char **argv) { CmdLine cmd; float fDistRatio = 0.8; std::string sSfM_Data_Filename; std::string sFeatDirectory = ""; int max_feature_count_per_image = -1; //required cmd.add(make_option('i', sSfM_Data_Filename, "input_file")); cmd.add(make_option('f', sFeatDirectory, "feat_dir")); // optional cmd.add(make_option('c', max_feature_count_per_image, "max_feature_count")); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string &s) { OPENMVG_LOG_ERROR << "Usage: " << argv[0] << '\n' << "[-i|--input_file] a SfM_Data file\n" << "[-f|--feat_dir path] output path where features are stored\n" << "--- Optional ---\n" << "[-c|--max_feature_count number] max_feature count per image (i.e 1000)."; OPENMVG_LOG_ERROR << s; return EXIT_FAILURE; } OPENMVG_LOG_INFO << " You called : " << "\n" << argv[0] << "\n" << "--input_file " << sSfM_Data_Filename << "\n" << "--feat_dir " << sFeatDirectory << "\n"; if (sFeatDirectory.empty() || !stlplus::is_folder(sFeatDirectory)) { OPENMVG_LOG_ERROR << "It is an invalid feature directory"; return EXIT_FAILURE; } //--------------------------------------- // Read SfM Scene (image view & intrinsics data) //--------------------------------------- SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS))) { OPENMVG_LOG_ERROR << "The input SfM_Data file \"" << sSfM_Data_Filename << "\" cannot be read."; return EXIT_FAILURE; } //--------------------------------------- // Load SfM Scene regions //--------------------------------------- // Init the regions_type from the image describer file (used for image regions extraction) using namespace openMVG::features; const std::string sImage_describer = stlplus::create_filespec(sFeatDirectory, "image_describer", "json"); std::unique_ptr<Regions> regions_type = Init_region_type_from_file(sImage_describer); if (!regions_type) { OPENMVG_LOG_ERROR << "Invalid: " << sImage_describer << " regions type file."; return EXIT_FAILURE; } system::LoggerProgress progress; // Load the corresponding view regions std::shared_ptr<Regions_Provider> regions_provider = (cmd.used('c') && max_feature_count_per_image != -1) ? std::make_shared<Preemptive_Regions_Provider>(max_feature_count_per_image) : std::make_shared<Regions_Provider>(); if (!regions_provider->load(sfm_data, sFeatDirectory, regions_type, &progress)) { OPENMVG_LOG_ERROR << "Invalid regions."; return EXIT_FAILURE; } // Select the pairs const Pair_Set pairs = exhaustivePairs(sfm_data.GetViews().size()); // Compute matches for a reference implementation (Brute Force L2) // - and compare the accuracy and timing of some other method // - accuracy is defined as the median percentage of similar index retrieved const std::vector<std::string> matcher_to_evaluate = { "brute_force_l2", "hnsw_l1", "hnsw_l2", "ann_l2", "cascade_l2", "fast_cascade_l2" }; OPENMVG_LOG_INFO << "Going to bench: "; for (const auto & method : matcher_to_evaluate) { OPENMVG_LOG_INFO << "- " << method; } struct collected_data { double time = 0.0; double accuracy = 0.0; }; std::map<std::string, collected_data> collected_stats; std::unique_ptr<Matcher> collectionMatcher; PairWiseMatches reference_matches; for (const auto & method : matcher_to_evaluate) { if (method == "brute_force_l2") collectionMatcher.reset(new Matcher_Regions(fDistRatio, BRUTE_FORCE_L2)); else if (method == "hnsw_l1") collectionMatcher.reset(new Matcher_Regions(fDistRatio, HNSW_L1)); else if (method == "hnsw_l2") collectionMatcher.reset(new Matcher_Regions(fDistRatio, HNSW_L2)); else if (method == "ann_l2") collectionMatcher.reset(new Matcher_Regions(fDistRatio, ANN_L2)); else if (method == "cascade_l2") collectionMatcher.reset(new Matcher_Regions(fDistRatio, CASCADE_HASHING_L2)); else if (method == "fast_cascade_l2") collectionMatcher.reset(new Cascade_Hashing_Matcher_Regions(fDistRatio)); else OPENMVG_LOG_ERROR << "Invalid Regions Matcher: " << method; collected_data data; if (method == "brute_force_l2") // Populate the reference matches { system::Timer timer; collectionMatcher->Match(regions_provider, pairs, reference_matches, &progress); data.time = timer.elapsed(); collected_stats[method] = data; } else // Compute corresponding indexes and compare them against the "GT" { system::Timer timer; PairWiseMatches matches; collectionMatcher->Match(regions_provider, pairs, matches, &progress); data.time = timer.elapsed(); // Compute accuracy // - percentage of correct retrieved index to the "GT" std::vector<double> accuracy_per_pair; for (const auto ref_matches_it : reference_matches) { const Pair pair = ref_matches_it.first; const auto & matches_ref = ref_matches_it.second; if (matches.count(pair) != 0) { const auto & matches_to_compare = matches[pair]; const std::set<IndMatch> set_bf( matches_ref.cbegin(), matches_ref.cend()); const std::set<IndMatch> set_compare( matches_to_compare.cbegin(), matches_to_compare.cend()); const size_t repetability_count = intersection_size(set_bf, set_compare); accuracy_per_pair.emplace_back( repetability_count / static_cast<double>(set_bf.size())); } } double min, max, mean, median; minMaxMeanMedian(accuracy_per_pair.cbegin(), accuracy_per_pair.cend(), min, max, mean, median); data.accuracy = median; collected_stats[method] = data; } } // Print results: for (const auto & method : matcher_to_evaluate) { OPENMVG_LOG_INFO << "Method: " << method << "\n" << "time(seconds): " << collected_stats[method].time; if (method != "brute_force_l2") OPENMVG_LOG_INFO << "accuracy(percent): " << collected_stats[method].accuracy; } return EXIT_SUCCESS; }
8,002
C++
.cpp
201
35.054726
107
0.662762
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,802
main_SfM.cpp
openMVG_openMVG/src/software/SfM/main_SfM.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2021 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/cameras/Camera_Common.hpp" #include "openMVG/cameras/Cameras_Common_command_line_helper.hpp" #include "openMVG/sfm/pipelines/sfm_features_provider.hpp" #include "openMVG/sfm/pipelines/sfm_matches_provider.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/sfm/sfm_report.hpp" #include "openMVG/sfm/sfm_view.hpp" #include "openMVG/system/timer.hpp" #include "openMVG/types.hpp" // SfM Engines #include "openMVG/sfm/pipelines/global/GlobalSfM_rotation_averaging.hpp" #include "openMVG/sfm/pipelines/global/GlobalSfM_translation_averaging.hpp" #include "openMVG/sfm/pipelines/global/sfm_global_engine_relative_motions.hpp" #include "openMVG/sfm/pipelines/sequential/sequential_SfM.hpp" #include "openMVG/sfm/pipelines/sequential/sequential_SfM2.hpp" #include "openMVG/sfm/pipelines/sequential/SfmSceneInitializerMaxPair.hpp" #include "openMVG/sfm/pipelines/sequential/SfmSceneInitializerStellar.hpp" #include "openMVG/sfm/pipelines/stellar/sfm_stellar_engine.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cstdlib> #include <memory> #include <string> #include <utility> using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::sfm; enum class ESfMSceneInitializer { INITIALIZE_EXISTING_POSES, INITIALIZE_MAX_PAIR, INITIALIZE_AUTO_PAIR, INITIALIZE_STELLAR }; enum class ESfMEngine { INCREMENTAL, INCREMENTALV2, GLOBAL, STELLAR }; bool StringToEnum ( const std::string & str, ESfMEngine & sfm_engine ) { const std::map<std::string, ESfMEngine> string_to_enum_mapping = { {"INCREMENTAL", ESfMEngine::INCREMENTAL}, {"INCREMENTALV2", ESfMEngine::INCREMENTALV2}, {"GLOBAL", ESfMEngine::GLOBAL}, {"STELLAR", ESfMEngine::STELLAR}, }; const auto it = string_to_enum_mapping.find(str); if (it == string_to_enum_mapping.end()) return false; sfm_engine = it->second; return true; } bool StringToEnum ( const std::string & str, ESfMSceneInitializer & scene_initializer ) { const std::map<std::string, ESfMSceneInitializer> string_to_enum_mapping = { {"EXISTING_POSE", ESfMSceneInitializer::INITIALIZE_EXISTING_POSES}, {"MAX_PAIR", ESfMSceneInitializer::INITIALIZE_MAX_PAIR}, {"AUTO_PAIR", ESfMSceneInitializer::INITIALIZE_AUTO_PAIR}, {"STELLAR", ESfMSceneInitializer::INITIALIZE_STELLAR}, }; const auto it = string_to_enum_mapping.find(str); if (it == string_to_enum_mapping.end()) return false; scene_initializer = it->second; return true; } bool StringToEnum_EGraphSimplification ( const std::string & str, EGraphSimplification & graph_simplification ) { const std::map<std::string, EGraphSimplification> string_to_enum_mapping = { {"NONE", EGraphSimplification::NONE}, {"MST_X", EGraphSimplification::MST_X}, {"STAR_X", EGraphSimplification::STAR_X}, }; auto it = string_to_enum_mapping.find(str); if (it == string_to_enum_mapping.end()) return false; graph_simplification = it->second; return true; } /// From 2 given image filenames, find the two corresponding index in the View list bool computeIndexFromImageNames( const SfM_Data & sfm_data, const std::pair<std::string,std::string>& initialPairName, Pair& initialPairIndex) { if (initialPairName.first == initialPairName.second) { OPENMVG_LOG_ERROR << "Invalid image names. You cannot use the same image to initialize a pair."; return false; } initialPairIndex = {UndefinedIndexT, UndefinedIndexT}; /// List views filenames and find the one that correspond to the user ones: for (Views::const_iterator it = sfm_data.GetViews().begin(); it != sfm_data.GetViews().end(); ++it) { const View * v = it->second.get(); const std::string filename = stlplus::filename_part(v->s_Img_path); if (filename == initialPairName.first) { initialPairIndex.first = v->id_view; } else { if (filename == initialPairName.second) { initialPairIndex.second = v->id_view; } } } return (initialPairIndex.first != UndefinedIndexT && initialPairIndex.second != UndefinedIndexT); } int main(int argc, char **argv) { OPENMVG_LOG_INFO << "\n-----------------------------------------------------------" << "\n Structure from Motion:" << "\n-----------------------------------------------------------"; CmdLine cmd; // Common options: std::string filename_sfm_data, directory_match, filename_match, directory_output, engine_name = "INCREMENTAL"; // Bundle adjustment options: std::string sIntrinsic_refinement_options = "ADJUST_ALL"; std::string sExtrinsic_refinement_options = "ADJUST_ALL"; bool b_use_motion_priors = false; // Incremental SfM options int triangulation_method = static_cast<int>(ETriangulationMethod::DEFAULT); int resection_method = static_cast<int>(resection::SolverType::DEFAULT); int user_camera_model = PINHOLE_CAMERA_RADIAL3; // SfM v1 std::pair<std::string,std::string> initial_pair_string("",""); // SfM v2 std::string sfm_initializer_method = "STELLAR"; // Global SfM int rotation_averaging_method = int (ROTATION_AVERAGING_L2); int translation_averaging_method = int (TRANSLATION_AVERAGING_SOFTL1); // Common options cmd.add( make_option('i', filename_sfm_data, "input_file") ); cmd.add( make_option('m', directory_match, "match_dir") ); cmd.add( make_option('M', filename_match, "match_file") ); cmd.add( make_option('o', directory_output, "output_dir") ); cmd.add( make_option('s', engine_name, "sfm_engine") ); // Bundle adjustment options cmd.add( make_option('f', sIntrinsic_refinement_options, "refine_intrinsic_config") ); cmd.add( make_option('e', sExtrinsic_refinement_options, "refine_extrinsic_config") ); cmd.add( make_switch('P', "prior_usage") ); // Incremental SfM pipeline options cmd.add( make_option('t', triangulation_method, "triangulation_method")); cmd.add( make_option('r', resection_method, "resection_method")); cmd.add( make_option('c', user_camera_model, "camera_model") ); // Incremental SfM2 cmd.add( make_option('S', sfm_initializer_method, "sfm_initializer") ); // Incremental SfM1 cmd.add( make_option('a', initial_pair_string.first, "initial_pair_a") ); cmd.add( make_option('b', initial_pair_string.second, "initial_pair_b") ); // Global SfM cmd.add( make_option('R', rotation_averaging_method, "rotationAveraging") ); cmd.add( make_option('T', translation_averaging_method, "translationAveraging") ); // Stellar SfM std::string graph_simplification = "MST_X"; int graph_simplification_value = 5; cmd.add( make_option('G', graph_simplification, "graph_simplification") ); cmd.add( make_option('g', graph_simplification_value, "graph_simplification_value") ); try { if (argc == 1) throw std::string("Invalid parameter."); cmd.process(argc, argv); } catch (const std::string& s) { OPENMVG_LOG_INFO << "Usage: " << argv[0] << '\n' << "[Required]\n" << "[-i|--input_file] path to a SfM_Data scene\n" << "[-m|--match_dir] path to the matches that corresponds to the provided SfM_Data scene\n" << "[-o|--output_dir] path where the output data will be stored\n" << "[-s|--sfm_engine] Type of SfM Engine to use for the reconstruction\n" << "\t INCREMENTAL : add image sequentially to a 2 view seed\n" << "\t INCREMENTALV2 : add image sequentially to a 2 or N view seed (experimental)\n" << "\t GLOBAL : initialize globally rotation and translations\n" << "\t STELLAR : n-uplets local motion refinements + global SfM\n" << "\n\n" << "[Optional parameters]\n" << "\n\n" << "[Common]\n" << "[-M|--match_file] path to the match file to use (i.e matches.f.txt or matches.f.bin)\n" << "[-f|--refine_intrinsic_config] Intrinsic parameters refinement option\n" << "\t ADJUST_ALL -> refine all existing parameters (default) \n" << "\t NONE -> intrinsic parameters are held as constant\n" << "\t ADJUST_FOCAL_LENGTH -> refine only the focal length\n" << "\t ADJUST_PRINCIPAL_POINT -> refine only the principal point position\n" << "\t ADJUST_DISTORTION -> refine only the distortion coefficient(s) (if any)\n" << "\t -> NOTE: options can be combined thanks to '|'\n" << "\t ADJUST_FOCAL_LENGTH|ADJUST_PRINCIPAL_POINT\n" << "\t\t-> refine the focal length & the principal point position\n" << "\t ADJUST_FOCAL_LENGTH|ADJUST_DISTORTION\n" << "\t\t-> refine the focal length & the distortion coefficient(s) (if any)\n" << "\t ADJUST_PRINCIPAL_POINT|ADJUST_DISTORTION\n" << "\t\t-> refine the principal point position & the distortion coefficient(s) (if any)\n" << "[-e|--refine_extrinsic_config] Extrinsic parameters refinement option\n" << "\t ADJUST_ALL -> refine all existing parameters (default) \n" << "\t NONE -> extrinsic parameters are held as constant\n" << "[-P|--prior_usage] Enable usage of motion priors (i.e GPS positions) (default: false)\n" << "\n\n" << "[Engine specifics]\n" << "\n\n" << "[INCREMENTAL]\n" << "\t[-a|--initial_pair_a] filename of the first image (without path)\n" << "\t[-b|--initial_pair_b] filename of the second image (without path)\n" << "\t[-c|--camera_model] Camera model type for view with unknown intrinsic:\n" << "\t\t 1: Pinhole \n" << "\t\t 2: Pinhole radial 1\n" << "\t\t 3: Pinhole radial 3 (default)\n" << "\t\t 4: Pinhole radial 3 + tangential 2\n" << "\t\t 5: Pinhole fisheye\n" << "\t[--triangulation_method] triangulation method (default=" << triangulation_method << "):\n" << "\t\t" << static_cast<int>(ETriangulationMethod::DIRECT_LINEAR_TRANSFORM) << ": DIRECT_LINEAR_TRANSFORM\n" << "\t\t" << static_cast<int>(ETriangulationMethod::L1_ANGULAR) << ": L1_ANGULAR\n" << "\t\t" << static_cast<int>(ETriangulationMethod::LINFINITY_ANGULAR) << ": LINFINITY_ANGULAR\n" << "\t\t" << static_cast<int>(ETriangulationMethod::INVERSE_DEPTH_WEIGHTED_MIDPOINT) << ": INVERSE_DEPTH_WEIGHTED_MIDPOINT\n" << "\t[--resection_method] resection/pose estimation method (default=" << resection_method << "):\n" << "\t\t" << static_cast<int>(resection::SolverType::DLT_6POINTS) << ": DIRECT_LINEAR_TRANSFORM 6Points | does not use intrinsic data\n" << "\t\t" << static_cast<int>(resection::SolverType::P3P_KE_CVPR17) << ": P3P_KE_CVPR17\n" << "\t\t" << static_cast<int>(resection::SolverType::P3P_KNEIP_CVPR11) << ": P3P_KNEIP_CVPR11\n" << "\t\t" << static_cast<int>(resection::SolverType::P3P_NORDBERG_ECCV18) << ": P3P_NORDBERG_ECCV18\n" << "\t\t" << static_cast<int>(resection::SolverType::P3P_DING_CVPR23) << ": P3P_DING_CVPR23\n" << "\t\t" << static_cast<int>(resection::SolverType::UP2P_KUKELOVA_ACCV10) << ": UP2P_KUKELOVA_ACCV10 | 2Points | upright camera\n" << "\n\n" << "[INCREMENTALV2]\n" << "\t[-S|--sfm_initializer] Choose the SfM initializer method:\n" << "\t\t 'EXISTING_POSE'-> Initialize the reconstruction from the existing sfm_data camera poses\n" << "\t\t 'MAX_PAIR'-> Initialize the reconstruction from the pair that has the most of matches\n" << "\t\t 'AUTO_PAIR'-> Initialize the reconstruction with a pair selected automatically\n" << "\t\t 'STELLAR'-> Initialize the reconstruction with a 'stellar' reconstruction\n" << "\t[-c|--camera_model] Camera model type for view with unknown intrinsic:\n" << "\t\t 1: Pinhole \n" << "\t\t 2: Pinhole radial 1\n" << "\t\t 3: Pinhole radial 3 (default)\n" << "\t\t 4: Pinhole radial 3 + tangential 2\n" << "\t\t 5: Pinhole fisheye\n" << "\t[--triangulation_method] triangulation method (default=" << triangulation_method << "):\n" << "\t\t" << static_cast<int>(ETriangulationMethod::DIRECT_LINEAR_TRANSFORM) << ": DIRECT_LINEAR_TRANSFORM\n" << "\t\t" << static_cast<int>(ETriangulationMethod::L1_ANGULAR) << ": L1_ANGULAR\n" << "\t\t" << static_cast<int>(ETriangulationMethod::LINFINITY_ANGULAR) << ": LINFINITY_ANGULAR\n" << "\t\t" << static_cast<int>(ETriangulationMethod::INVERSE_DEPTH_WEIGHTED_MIDPOINT) << ": INVERSE_DEPTH_WEIGHTED_MIDPOINT\n" << "\t[--resection_method] resection/pose estimation method (default=" << resection_method << "):\n" << "\t\t" << static_cast<int>(resection::SolverType::DLT_6POINTS) << ": DIRECT_LINEAR_TRANSFORM 6Points | does not use intrinsic data\n" << "\t\t" << static_cast<int>(resection::SolverType::P3P_KE_CVPR17) << ": P3P_KE_CVPR17\n" << "\t\t" << static_cast<int>(resection::SolverType::P3P_KNEIP_CVPR11) << ": P3P_KNEIP_CVPR11\n" << "\t\t" << static_cast<int>(resection::SolverType::P3P_NORDBERG_ECCV18) << ": P3P_NORDBERG_ECCV18\n" << "\t\t" << static_cast<int>(resection::SolverType::P3P_DING_CVPR23) << ": P3P_DING_CVPR23\n" << "\t\t" << static_cast<int>(resection::SolverType::UP2P_KUKELOVA_ACCV10) << ": UP2P_KUKELOVA_ACCV10 | 2Points | upright camera\n" << "\n\n" << "[GLOBAL]\n" << "\t[-R|--rotationAveraging]\n" << "\t\t 1 -> L1 minimization\n" << "\t\t 2 -> L2 minimization (default)\n" << "\t[-T|--translationAveraging]:\n" << "\t\t 1 -> L1 minimization\n" << "\t\t 2 -> L2 minimization of sum of squared Chordal distances\n" << "\t\t 3 -> SoftL1 minimization (default)\n" << "\t\t 4 -> LiGT: Linear Global Translation constraints from rotation and matches\n" << "[STELLAR]\n" << "\t[-G|--graph_simplification]\n" << "\t\t -> NONE\n" << "\t\t -> MST_X\n" << "\t\t -> STAR_X\n" << "\t[-g|--graph_simplification_value]\n" << "\t\t -> Number (default: " << graph_simplification_value << ")"; OPENMVG_LOG_ERROR << s; return EXIT_FAILURE; } b_use_motion_priors = cmd.used('P'); // Check validity of command line parameters: if ( !isValid(static_cast<ETriangulationMethod>(triangulation_method))) { OPENMVG_LOG_ERROR << "Invalid triangulation method"; return EXIT_FAILURE; } if ( !isValid(openMVG::cameras::EINTRINSIC(user_camera_model)) ) { OPENMVG_LOG_ERROR << "Invalid camera type"; return EXIT_FAILURE; } const cameras::Intrinsic_Parameter_Type intrinsic_refinement_options = cameras::StringTo_Intrinsic_Parameter_Type(sIntrinsic_refinement_options); if (intrinsic_refinement_options == static_cast<cameras::Intrinsic_Parameter_Type>(0) ) { OPENMVG_LOG_ERROR << "Invalid input for Bundle Adjustment Intrinsic parameter refinement option"; return EXIT_FAILURE; } const sfm::Extrinsic_Parameter_Type extrinsic_refinement_options = sfm::StringTo_Extrinsic_Parameter_Type(sExtrinsic_refinement_options); if (extrinsic_refinement_options == static_cast<sfm::Extrinsic_Parameter_Type>(0) ) { OPENMVG_LOG_ERROR << "Invalid input for the Bundle Adjustment Extrinsic parameter refinement option"; return EXIT_FAILURE; } ESfMSceneInitializer scene_initializer_enum; if (!StringToEnum(sfm_initializer_method, scene_initializer_enum)) { OPENMVG_LOG_ERROR << "Invalid input for the SfM initializer option"; return EXIT_FAILURE; } ESfMEngine sfm_engine_type; if (!StringToEnum(engine_name, sfm_engine_type)) { OPENMVG_LOG_ERROR << "Invalid input for the SfM Engine type"; return EXIT_FAILURE; } if (rotation_averaging_method < ROTATION_AVERAGING_L1 || rotation_averaging_method > ROTATION_AVERAGING_L2 ) { OPENMVG_LOG_ERROR << "Rotation averaging method is invalid"; return EXIT_FAILURE; } #ifndef USE_PATENTED_LIGT if (translation_averaging_method == TRANSLATION_LIGT) { OPENMVG_LOG_ERROR << "OpenMVG was not compiled with USE_PATENTED_LIGT cmake option"; return EXIT_FAILURE; } #endif if (translation_averaging_method < TRANSLATION_AVERAGING_L1 || translation_averaging_method > TRANSLATION_LIGT ) { OPENMVG_LOG_ERROR << "Translation averaging method is invalid"; return EXIT_FAILURE; } EGraphSimplification graph_simplification_method; if (!StringToEnum_EGraphSimplification(graph_simplification, graph_simplification_method)) { OPENMVG_LOG_ERROR << "Cannot recognize graph simplification method"; return EXIT_FAILURE; } if (graph_simplification_value <= 1) { OPENMVG_LOG_ERROR << "graph simplification value must be > 1"; return EXIT_FAILURE; } if (directory_output.empty()) { OPENMVG_LOG_ERROR << "It is an invalid output directory"; return EXIT_FAILURE; } // SfM related // Load input SfM_Data scene SfM_Data sfm_data; const ESfM_Data sfm_data_loading_etypes = scene_initializer_enum == ESfMSceneInitializer::INITIALIZE_EXISTING_POSES ? ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS) : ESfM_Data(VIEWS|INTRINSICS); if (!Load(sfm_data, filename_sfm_data, sfm_data_loading_etypes)) { OPENMVG_LOG_ERROR << "The input SfM_Data file \""<< filename_sfm_data << "\" cannot be read."; return EXIT_FAILURE; } if (!stlplus::folder_exists(directory_output)) { if (!stlplus::folder_create(directory_output)) { OPENMVG_LOG_ERROR << "Cannot create the output directory"; return EXIT_FAILURE; } } // // Match and features // if (directory_match.empty() && !filename_match.empty() && stlplus::file_exists(filename_match)) { directory_match = stlplus::folder_part(filename_match); filename_match = stlplus::filename_part(filename_match); } // Init the regions_type from the image describer file (used for image regions extraction) using namespace openMVG::features; const std::string sImage_describer = stlplus::create_filespec(directory_match, "image_describer", "json"); std::unique_ptr<Regions> regions_type = Init_region_type_from_file(sImage_describer); if (!regions_type) { OPENMVG_LOG_ERROR << "Invalid: " << sImage_describer << " regions type file."; return EXIT_FAILURE; } // Features reading std::shared_ptr<Features_Provider> feats_provider = std::make_shared<Features_Provider>(); if (!feats_provider->load(sfm_data, directory_match, regions_type)) { OPENMVG_LOG_ERROR << "Cannot load view corresponding features in directory: " << directory_match << "."; return EXIT_FAILURE; } // Matches reading std::shared_ptr<Matches_Provider> matches_provider = std::make_shared<Matches_Provider>(); if // Try to read the provided match filename or the default one (matches.f.txt/bin) ( !(matches_provider->load(sfm_data, stlplus::create_filespec(directory_match, filename_match)) || matches_provider->load(sfm_data, stlplus::create_filespec(directory_match, "matches.f.txt")) || matches_provider->load(sfm_data, stlplus::create_filespec(directory_match, "matches.f.bin")) || matches_provider->load(sfm_data, stlplus::create_filespec(directory_match, "matches.e.txt")) || matches_provider->load(sfm_data, stlplus::create_filespec(directory_match, "matches.e.bin"))) ) { OPENMVG_LOG_ERROR << "Cannot load the match file."; return EXIT_FAILURE; } std::unique_ptr<SfMSceneInitializer> scene_initializer; switch(scene_initializer_enum) { case ESfMSceneInitializer::INITIALIZE_AUTO_PAIR: OPENMVG_LOG_ERROR << "Not yet implemented."; return EXIT_FAILURE; break; case ESfMSceneInitializer::INITIALIZE_MAX_PAIR: scene_initializer.reset(new SfMSceneInitializerMaxPair(sfm_data, feats_provider.get(), matches_provider.get())); break; case ESfMSceneInitializer::INITIALIZE_EXISTING_POSES: scene_initializer.reset(new SfMSceneInitializer(sfm_data, feats_provider.get(), matches_provider.get())); break; case ESfMSceneInitializer::INITIALIZE_STELLAR: scene_initializer.reset(new SfMSceneInitializerStellar(sfm_data, feats_provider.get(), matches_provider.get())); break; default: OPENMVG_LOG_ERROR << "Unknown SFM Scene initializer method"; return EXIT_FAILURE; } if (!scene_initializer) { OPENMVG_LOG_ERROR << "Invalid scene initializer."; return EXIT_FAILURE; } std::unique_ptr<ReconstructionEngine> sfm_engine; switch (sfm_engine_type) { case ESfMEngine::INCREMENTAL: { SequentialSfMReconstructionEngine * engine = new SequentialSfMReconstructionEngine( sfm_data, directory_output, stlplus::create_filespec(directory_output, "Reconstruction_Report.html")); // Configuration: engine->SetFeaturesProvider(feats_provider.get()); engine->SetMatchesProvider(matches_provider.get()); // Configure reconstruction parameters engine->SetUnknownCameraType(EINTRINSIC(user_camera_model)); engine->SetTriangulationMethod(static_cast<ETriangulationMethod>(triangulation_method)); engine->SetResectionMethod(static_cast<resection::SolverType>(resection_method)); // Handle Initial pair parameter if (!initial_pair_string.first.empty() && !initial_pair_string.second.empty()) { Pair initial_pair_index; if (!computeIndexFromImageNames(sfm_data, initial_pair_string, initial_pair_index)) { OPENMVG_LOG_ERROR << "Could not find the initial pairs <" << initial_pair_string.first << ", " << initial_pair_string.second << ">!"; return EXIT_FAILURE; } engine->setInitialPair(initial_pair_index); } sfm_engine.reset(engine); } break; case ESfMEngine::INCREMENTALV2: { SequentialSfMReconstructionEngine2 * engine = new SequentialSfMReconstructionEngine2( scene_initializer.get(), sfm_data, directory_output, stlplus::create_filespec(directory_output, "Reconstruction_Report.html")); // Configuration: engine->SetFeaturesProvider(feats_provider.get()); engine->SetMatchesProvider(matches_provider.get()); // Configure reconstruction parameters engine->SetTriangulationMethod(static_cast<ETriangulationMethod>(triangulation_method)); engine->SetUnknownCameraType(EINTRINSIC(user_camera_model)); engine->SetResectionMethod(static_cast<resection::SolverType>(resection_method)); sfm_engine.reset(engine); } break; case ESfMEngine::GLOBAL: { GlobalSfMReconstructionEngine_RelativeMotions * engine = new GlobalSfMReconstructionEngine_RelativeMotions( sfm_data, directory_output, stlplus::create_filespec(directory_output, "Reconstruction_Report.html")); // Configuration: engine->SetFeaturesProvider(feats_provider.get()); engine->SetMatchesProvider(matches_provider.get()); // Configure motion averaging method engine->SetRotationAveragingMethod(ERotationAveragingMethod(rotation_averaging_method)); engine->SetTranslationAveragingMethod(ETranslationAveragingMethod(translation_averaging_method)); sfm_engine.reset(engine); } break; case ESfMEngine::STELLAR: { StellarSfMReconstructionEngine * engine = new StellarSfMReconstructionEngine( sfm_data, directory_output, stlplus::create_filespec(directory_output, "Reconstruction_Report.html")); // Configure the features_provider & the matches_provider engine->SetFeaturesProvider(feats_provider.get()); engine->SetMatchesProvider(matches_provider.get()); // Configure reconstruction parameters engine->SetGraphSimplification(graph_simplification_method, graph_simplification_value); sfm_engine.reset(engine); } break; default: break; } if (!sfm_engine) { OPENMVG_LOG_ERROR << "Cannot create the requested SfM Engine."; return EXIT_FAILURE; } sfm_engine->Set_Intrinsics_Refinement_Type(intrinsic_refinement_options); sfm_engine->Set_Extrinsics_Refinement_Type(extrinsic_refinement_options); sfm_engine->Set_Use_Motion_Prior(b_use_motion_priors); //--------------------------------------- // Sequential reconstruction process //--------------------------------------- openMVG::system::Timer timer; if (sfm_engine->Process()) { OPENMVG_LOG_INFO << " Total Sfm took (s): " << timer.elapsed(); OPENMVG_LOG_INFO << "...Generating SfM_Report.html"; Generate_SfM_Report(sfm_engine->Get_SfM_Data(), stlplus::create_filespec(directory_output, "SfMReconstruction_Report.html")); //-- Export to disk computed scene (data & viewable results) OPENMVG_LOG_INFO << "...Export SfM_Data to disk."; Save(sfm_engine->Get_SfM_Data(), stlplus::create_filespec(directory_output, "sfm_data", ".bin"), ESfM_Data(ALL)); Save(sfm_engine->Get_SfM_Data(), stlplus::create_filespec(directory_output, "cloud_and_poses", ".ply"), ESfM_Data(ALL)); return EXIT_SUCCESS; } return EXIT_FAILURE; }
25,475
C++
.cpp
564
40.25
142
0.683791
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,803
main_MatchingRetrievalQuality.cpp
openMVG_openMVG/src/software/SfM/main_MatchingRetrievalQuality.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2020 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/features/descriptor.hpp" #include "openMVG/features/feature.hpp" #include "openMVG/matching/indMatch.hpp" #include "openMVG/matching/indMatch_utils.hpp" #include "openMVG/matching/pairwiseAdjacencyDisplay.hpp" #include "openMVG/matching_image_collection/Pair_Builder.hpp" #include "openMVG/matching_image_collection/Retrieval_Helpers.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/stl/stl.hpp" #include "openMVG/system/timer.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cstdlib> #include <iostream> #include <iterator> #include <memory> #include <string> using namespace openMVG; using namespace openMVG::matching; using namespace openMVG::sfm; using namespace openMVG::retrieval; int main(int argc, char **argv) { CmdLine cmd; std::string sSfM_Data_Filename; std::string sGTMatchFilename; std::string sInputPairFilename; std::string sInputSimFile; // required cmd.add(make_option('i', sSfM_Data_Filename, "input_file")); cmd.add(make_option('p', sInputPairFilename, "pair_file")); cmd.add(make_option('s', sInputSimFile, "sim_file")); cmd.add(make_option('g', sGTMatchFilename, "gt_matches")); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string &s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_file] a SfM_Data file containing the GT " "reconstruction\n" << "[-s|--sim_file] use a pairwise similarity file to compute mAP\n" << "\n[Optional]\n" << "[-p|--pair_file] alternatively to the sim file, the pair file you " "want to compare to your GT pairs (mAP won't be computed)\n" << "[-g|--gt_matches] a matches.bin/.txt file (i.e " "matches.f.txt), else pairs from the input sfm_data are used\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } std::cout << " You called : " << "\n" << argv[0] << "\n" << "--input_file " << sSfM_Data_Filename << "\n" << "--sim_file " << sInputSimFile << "\n" << "--pair_file " << sInputPairFilename << "\n" << "--gt_matches " << sGTMatchFilename << "\n" << std::endl; // Are the gt pairs loaded from matches or are they extracted from sfm_data? const bool gt_from_matches = !sGTMatchFilename.empty(); // Are the putative pairs loaded from sim file or from a pair file const bool putative_from_sim = !sInputSimFile.empty(); if (gt_from_matches && !stlplus::file_exists(sGTMatchFilename)) { std::cerr << "It is an invalid --gt_matches file" << std::endl; return EXIT_FAILURE; } if (putative_from_sim && !stlplus::file_exists(sInputSimFile)) { std::cerr << "It is an invalid --sim_file similarity file" << std::endl; return EXIT_FAILURE; } if (!putative_from_sim && (sInputPairFilename.empty() || !stlplus::file_exists(sInputPairFilename))) { std::cerr << "It is an invalid --pair_file pair file" << std::endl; return EXIT_FAILURE; } PairWiseMatches gt_pairwise_matches; //--------------------------------------- // Read SfM Scene (image view) //--------------------------------------- ESfM_Data sfm_data_flags = gt_from_matches ? ESfM_Data(VIEWS) : ESfM_Data(VIEWS | STRUCTURE); SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(sfm_data_flags))) { std::cerr << std::endl << "The input SfM_Data file \"" << sSfM_Data_Filename << "\" cannot be read." << std::endl; return EXIT_FAILURE; } Pair_Set gt_pairs; if (gt_from_matches) { if (!(Load(gt_pairwise_matches, sGTMatchFilename))) { std::cerr << "Cannot load input GT matches file"; return EXIT_FAILURE; } std::cout << "\t GT RESULTS LOADED;" << " #pairs: " << gt_pairwise_matches.size() << std::endl; gt_pairs = getPairs(gt_pairwise_matches); // clear some memory gt_pairwise_matches.clear(); } else { for (auto &track : sfm_data.GetLandmarks()) { const auto &obs = track.second.obs; for (auto obs_it1 = obs.cbegin(); obs_it1 != obs.cend(); ++obs_it1) { for (auto obs_it2 = std::next(obs_it1, 1); obs_it2 != obs.cend(); ++obs_it2) { gt_pairs.insert({std::min(obs_it1->first, obs_it2->first), std::max(obs_it1->first, obs_it2->first)}); } } } } Pair_Set putative_pairs; IndexedPairwiseSimilarity<std::greater<double>> ordered_results; if (putative_from_sim) { if (!loadPairwiseSimilarityScores(sInputSimFile, ordered_results)) { std::cerr << "Cannot load input sim file"; return EXIT_FAILURE; } for (const auto &indexed_pairwise_score : ordered_results) { IndexT i = indexed_pairwise_score.first; for (const auto &tuple_score : indexed_pairwise_score.second) { const IndexT j = tuple_score.second; putative_pairs.insert({std::min(i, j), std::max(i, j)}); } } } else { if (!loadPairs(sfm_data.GetViews().size(), sInputPairFilename, putative_pairs)) { std::cerr << "Cannot load input pair file"; return EXIT_FAILURE; } } std::cout << "\t PUTATIVE RESULTS LOADED;" << " #pairs: " << putative_pairs.size() << std::endl; // Computing retrieval statistics: // See https://en.wikipedia.org/wiki/Sensitivity_and_specificity // // TP: Pair count that must be found // FP: Pair count that are found that should not be found std::set<Pair> common_pairs; std::set_intersection(gt_pairs.cbegin(), gt_pairs.cend(), putative_pairs.cbegin(), putative_pairs.cend(), std::inserter(common_pairs, common_pairs.begin())); // TP: correctly identified const int true_positive_count = common_pairs.size(); // FN: missed - not detected const int false_negative_count = gt_pairs.size() - common_pairs.size(); // FP: detected by we should not have const int false_positive_count = putative_pairs.size() - common_pairs.size(); // TN: correctly rejected // const int true_negative_count = // True positive = correctly identified // False positive = incorrectly identified // True negative = correctly rejected // False negative = incorrectly rejected // Recall, same as TPR(True Positive Rate) const double recall = true_positive_count / static_cast<float>(true_positive_count + false_negative_count); const double precision = true_positive_count / static_cast<float>(true_positive_count + false_positive_count); std::cout << "Retrieval statistics:\n" << "\t#GT pairs: " << gt_pairs.size() << "\n" << "\t#Putative pairs: " << putative_pairs.size() << "\n" << "\n" << "\tTrue positive count: " << true_positive_count << "\n" << "\tFalse negative count: " << false_negative_count << "\n" << "\n" //<< "\tFalse positive count: " << false_positive_count << "\n" << "\tRecall: " << recall << "\n" << "\tprecision: " << precision << "\n" << std::endl; // mAP computation if (putative_from_sim) { double average_precision = 0.0; for (const auto &indexed_pairwise_score : ordered_results) { const IndexT i = indexed_pairwise_score.first; uint32_t counter = 0; uint32_t counter_TP = 0; double cur_AP = 0.; for (const auto &tuple_score : indexed_pairwise_score.second) { const IndexT j = tuple_score.second; bool is_GT = (gt_pairs.count({std::min(i, j), std::max(i, j)}) > 0); counter++; if (is_GT) { counter_TP++; cur_AP += counter_TP / static_cast<double>(counter); } } uint32_t local_num_gt = 0; for (const auto &pair : gt_pairs) { // TODO: C++17 reduce local_num_gt = (pair.first == i || pair.second == i) ? local_num_gt + 1 : local_num_gt; } cur_AP = cur_AP / local_num_gt; average_precision += cur_AP; } double mAP = average_precision / ordered_results.size(); std::cout << "\tmAP: " << mAP << std::endl; } return EXIT_SUCCESS; }
8,786
C++
.cpp
209
35.703349
79
0.616608
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,805
main_PairGenerator.cpp
openMVG_openMVG/src/software/SfM/main_PairGenerator.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2019 Romuald PERROT // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/matching_image_collection/Pair_Builder.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <iostream> /** * @brief Current list of available pair mode * */ enum EPairMode { PAIR_EXHAUSTIVE = 0, // Build every combination of image pairs PAIR_CONTIGUOUS = 1 // Only consecutive image pairs (useful for video mode) }; using namespace openMVG; using namespace openMVG::sfm; void usage( const char* argv0 ) { std::cerr << "Usage: " << argv0 << '\n' << "[-i|--input_file] A SfM_Data file\n" << "[-o|--output_file] Output file where pairs are stored\n" << "\n[Optional]\n" << "[-m|--pair_mode] mode Pair generation mode\n" << " EXHAUSTIVE: Build all possible pairs. [default]\n" << " CONTIGUOUS: Build pairs for contiguous images (use it with --contiguous_count parameter)\n" << "[-c|--contiguous_count] X Number of contiguous links\n" << " X: will match 0 with (1->X), ...]\n" << " 2: will match 0 with (1,2), 1 with (2,3), ...\n" << " 3: will match 0 with (1,2,3), 1 with (2,3,4), ...\n" << std::endl; } // This executable computes pairs of images to be matched int main( int argc, char** argv ) { CmdLine cmd; std::string sSfMDataFilename; std::string sOutputPairsFilename; std::string sPairMode = "EXHAUSTIVE"; int iContiguousCount = -1; // Mandatory elements: cmd.add( make_option( 'i', sSfMDataFilename, "input_file" ) ); cmd.add( make_option( 'o', sOutputPairsFilename, "output_file" ) ); // Optional elements: cmd.add( make_option( 'm', sPairMode, "pair_mode" ) ); cmd.add( make_option( 'c', iContiguousCount, "contiguous_count" ) ); try { if ( argc == 1 ) throw std::string( "Invalid command line parameter." ); cmd.process( argc, argv ); } catch ( const std::string& s ) { usage( argv[ 0 ] ); std::cerr << "[Error] " << s << std::endl; return EXIT_FAILURE; } // 0. Parse parameters std::cout << " You called:\n" << argv[ 0 ] << "\n" << "--input_file : " << sSfMDataFilename << "\n" << "--output_file : " << sOutputPairsFilename << "\n" << "Optional parameters\n" << "--pair_mode : " << sPairMode << "\n" << "--contiguous_count : " << iContiguousCount << "\n" << std::endl; if ( sSfMDataFilename.empty() ) { usage( argv[ 0 ] ); std::cerr << "[Error] Input file not set." << std::endl; exit( EXIT_FAILURE ); } if ( sOutputPairsFilename.empty() ) { usage( argv[ 0 ] ); std::cerr << "[Error] Output file not set." << std::endl; exit( EXIT_FAILURE ); } EPairMode pairMode; if ( sPairMode == "EXHAUSTIVE" ) { pairMode = PAIR_EXHAUSTIVE; } else if ( sPairMode == "CONTIGUOUS" ) { if ( iContiguousCount == -1 ) { usage( argv[ 0 ] ); std::cerr << "[Error] Contiguous pair mode selected but contiguous_count not set." << std::endl; exit( EXIT_FAILURE ); } pairMode = PAIR_CONTIGUOUS; } // 1. Load SfM data scene std::cout << "Loading scene."; SfM_Data sfm_data; if ( !Load( sfm_data, sSfMDataFilename, ESfM_Data( VIEWS | INTRINSICS ) ) ) { std::cerr << std::endl << "The input SfM_Data file \"" << sSfMDataFilename << "\" cannot be read." << std::endl; exit( EXIT_FAILURE ); } const size_t NImage = sfm_data.GetViews().size(); // 2. Compute pairs std::cout << "Computing pairs." << std::endl; Pair_Set pairs; switch ( pairMode ) { case PAIR_EXHAUSTIVE: { pairs = exhaustivePairs( NImage ); break; } case PAIR_CONTIGUOUS: { pairs = contiguousWithOverlap( NImage, iContiguousCount ); break; } default: { std::cerr << "Unknown pair mode" << std::endl; exit( EXIT_FAILURE ); } } // 3. Save pairs std::cout << "Saving pairs." << std::endl; if ( !savePairs( sOutputPairsFilename, pairs ) ) { std::cerr << "Failed to save pairs to file: \"" << sOutputPairsFilename << "\"" << std::endl; exit( EXIT_FAILURE ); } return EXIT_SUCCESS; }
4,736
C++
.cpp
139
29.201439
121
0.593531
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,811
main_GeometricFilter.cpp
openMVG_openMVG/src/software/SfM/main_GeometricFilter.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2019 Pierre MOULON, Romuald PERROT // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/features/akaze/image_describer_akaze.hpp" #include "openMVG/features/descriptor.hpp" #include "openMVG/features/feature.hpp" #include "openMVG/graph/graph.hpp" #include "openMVG/graph/graph_stats.hpp" #include "openMVG/matching/indMatch.hpp" #include "openMVG/matching/indMatch_utils.hpp" #include "openMVG/matching/pairwiseAdjacencyDisplay.hpp" #include "openMVG/matching_image_collection/Cascade_Hashing_Matcher_Regions.hpp" #include "openMVG/matching_image_collection/E_ACRobust.hpp" #include "openMVG/matching_image_collection/E_ACRobust_Angular.hpp" #include "openMVG/matching_image_collection/Eo_Robust.hpp" #include "openMVG/matching_image_collection/F_ACRobust.hpp" #include "openMVG/matching_image_collection/GeometricFilter.hpp" #include "openMVG/matching_image_collection/H_ACRobust.hpp" #include "openMVG/matching_image_collection/Matcher_Regions.hpp" #include "openMVG/matching_image_collection/Pair_Builder.hpp" #include "openMVG/sfm/pipelines/sfm_features_provider.hpp" #include "openMVG/sfm/pipelines/sfm_regions_provider.hpp" #include "openMVG/sfm/pipelines/sfm_regions_provider_cache.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/stl/stl.hpp" #include "openMVG/system/timer.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cstdlib> #include <iostream> #include <locale> #include <memory> #include <string> using namespace openMVG; using namespace openMVG::matching; using namespace openMVG::robust; using namespace openMVG::sfm; using namespace openMVG::matching_image_collection; enum EGeometricModel { FUNDAMENTAL_MATRIX = 0, ESSENTIAL_MATRIX = 1, HOMOGRAPHY_MATRIX = 2, ESSENTIAL_MATRIX_ANGULAR = 3, ESSENTIAL_MATRIX_ORTHO = 4, ESSENTIAL_MATRIX_UPRIGHT = 5 }; /// Compute corresponding features between a series of views: /// - Load view images description (regions: features & descriptors) /// - Compute putative local feature matches (descriptors matching) /// - Compute geometric coherent feature matches (robust model estimation from putative matches) /// - Export computed data int main( int argc, char** argv ) { CmdLine cmd; // The scene std::string sSfM_Data_Filename; // The input matches std::string sPutativeMatchesFilename; // The output matches std::string sFilteredMatchesFilename; // The input pairs std::string sInputPairsFilename; // The output pairs std::string sOutputPairsFilename; std::string sGeometricModel = "f"; bool bForce = false; bool bGuided_matching = false; int imax_iteration = 2048; unsigned int ui_max_cache_size = 0; //required cmd.add( make_option( 'i', sSfM_Data_Filename, "input_file" ) ); cmd.add( make_option( 'o', sFilteredMatchesFilename, "output_file" ) ); cmd.add( make_option( 'm', sPutativeMatchesFilename, "matches" ) ); // Options cmd.add( make_option( 'p', sInputPairsFilename, "input_pairs" ) ); cmd.add( make_option( 's', sOutputPairsFilename, "output_pairs" ) ); cmd.add( make_option( 'g', sGeometricModel, "geometric_model" ) ); cmd.add( make_option( 'f', bForce, "force" ) ); cmd.add( make_option( 'r', bGuided_matching, "guided_matching" ) ); cmd.add( make_option( 'I', imax_iteration, "max_iteration" ) ); cmd.add( make_option( 'c', ui_max_cache_size, "cache_size" ) ); try { if ( argc == 1 ) throw std::string( "Invalid command line parameter." ); cmd.process( argc, argv ); } catch ( const std::string& s ) { OPENMVG_LOG_INFO << "Usage: " << argv[0] << '\n' << "[-i|--input_file] A SfM_Data file\n" << "[-m|--matches] (Input) matches filename\n" << "[-o|--output_file] (Output) filtered matches filename\n" << "\n[Optional]\n" << "[-p|--input_pairs] (Input) pairs filename\n" << "[-s|--output_pairs] (Output) filtered pairs filename\n" << "[-f|--force] Force to recompute data\n" << "[-g|--geometric_model]\n" << " (pairwise correspondences filtering thanks to robust model estimation):\n" << " f: (default) fundamental matrix,\n" << " e: essential matrix,\n" << " h: homography matrix.\n" << " a: essential matrix with an angular parametrization,\n" << " u: upright essential matrix with an angular parametrization,\n" << " o: orthographic essential matrix.\n" << "[-r|--guided_matching] Use the found model to improve the pairwise correspondences.\n" << "[-c|--cache_size]\n" << " Use a regions cache (only cache_size regions will be stored in memory)\n" << " If not used, all regions will be load in memory."; OPENMVG_LOG_INFO << s; return EXIT_FAILURE; } OPENMVG_LOG_INFO << " You called : " << "\n" << argv[0] << "\n" << "--input_file: " << sSfM_Data_Filename << "\n" << "--matches: " << sPutativeMatchesFilename << "\n" << "--output_file: " << sFilteredMatchesFilename << "\n" << "Optional parameters: " << "\n" << "--input_pairs " << sInputPairsFilename << "\n" << "--output_pairs " << sOutputPairsFilename << "\n" << "--force " << (bForce ? "true" : "false") << "\n" << "--geometric_model " << sGeometricModel << "\n" << "--guided_matching " << bGuided_matching << "\n" << "--cache_size " << ((ui_max_cache_size == 0) ? "unlimited" : std::to_string(ui_max_cache_size)); if ( sFilteredMatchesFilename.empty() ) { OPENMVG_LOG_ERROR << "It is an invalid output file"; return EXIT_FAILURE; } if ( sSfM_Data_Filename.empty() ) { OPENMVG_LOG_ERROR << "It is an invalid SfM file"; return EXIT_FAILURE; } if ( sPutativeMatchesFilename.empty() ) { OPENMVG_LOG_ERROR << "It is an invalid putative matche file"; return EXIT_FAILURE; } const std::string sMatchesDirectory = stlplus::folder_part( sPutativeMatchesFilename ); EGeometricModel eGeometricModelToCompute = FUNDAMENTAL_MATRIX; switch ( std::tolower(sGeometricModel[ 0 ], std::locale()) ) { case 'f': eGeometricModelToCompute = FUNDAMENTAL_MATRIX; break; case 'e': eGeometricModelToCompute = ESSENTIAL_MATRIX; break; case 'h': eGeometricModelToCompute = HOMOGRAPHY_MATRIX; break; case 'a': eGeometricModelToCompute = ESSENTIAL_MATRIX_ANGULAR; break; case 'u': eGeometricModelToCompute = ESSENTIAL_MATRIX_UPRIGHT; break; case 'o': eGeometricModelToCompute = ESSENTIAL_MATRIX_ORTHO; break; default: OPENMVG_LOG_ERROR << "Unknown geometric model"; return EXIT_FAILURE; } // ----------------------------- // - Load SfM_Data Views & intrinsics data // a. Load putative descriptor matches // [a.1] Filter matches with input pairs // b. Geometric filtering of putative matches // + Export some statistics // ----------------------------- //--------------------------------------- // Read SfM Scene (image view & intrinsics data) //--------------------------------------- SfM_Data sfm_data; if ( !Load( sfm_data, sSfM_Data_Filename, ESfM_Data( VIEWS | INTRINSICS ) ) ) { OPENMVG_LOG_ERROR << "The input SfM_Data file \"" << sSfM_Data_Filename << "\" cannot be read."; return EXIT_FAILURE; } //--------------------------------------- // Load SfM Scene regions //--------------------------------------- // Init the regions_type from the image describer file (used for image regions extraction) using namespace openMVG::features; // Consider that the image_describer.json is inside the matches directory (which is bellow the sfm_data.bin) const std::string sImage_describer = stlplus::create_filespec( sMatchesDirectory, "image_describer.json" ); std::unique_ptr<Regions> regions_type = Init_region_type_from_file( sImage_describer ); if ( !regions_type ) { OPENMVG_LOG_ERROR << "Invalid: " << sImage_describer << " regions type file."; return EXIT_FAILURE; } //--------------------------------------- // a. Compute putative descriptor matches // - Descriptor matching (according user method choice) // - Keep correspondences only if NearestNeighbor ratio is ok //--------------------------------------- // Load the corresponding view regions std::shared_ptr<Regions_Provider> regions_provider; if ( ui_max_cache_size == 0 ) { // Default regions provider (load & store all regions in memory) regions_provider = std::make_shared<Regions_Provider>(); } else { // Cached regions provider (load & store regions on demand) regions_provider = std::make_shared<Regions_Provider_Cache>( ui_max_cache_size ); } // Show the progress on the command line: system::LoggerProgress progress; if ( !regions_provider->load( sfm_data, sMatchesDirectory, regions_type, &progress ) ) { OPENMVG_LOG_ERROR << "Invalid regions."; return EXIT_FAILURE; } PairWiseMatches map_PutativeMatches; //--------------------------------------- // A. Load initial matches //--------------------------------------- if ( !Load( map_PutativeMatches, sPutativeMatchesFilename ) ) { OPENMVG_LOG_ERROR << "Failed to load the initial matches file."; return EXIT_FAILURE; } if ( !sInputPairsFilename.empty() ) { // Load input pairs OPENMVG_LOG_INFO << "Loading input pairs ..."; Pair_Set input_pairs; loadPairs( sfm_data.GetViews().size(), sInputPairsFilename, input_pairs ); // Filter matches with the given pairs OPENMVG_LOG_INFO << "Filtering matches with the given pairs."; map_PutativeMatches = getPairs( map_PutativeMatches, input_pairs ); } //--------------------------------------- // b. Geometric filtering of putative matches // - AContrario Estimation of the desired geometric model // - Use an upper bound for the a contrario estimated threshold //--------------------------------------- std::unique_ptr<ImageCollectionGeometricFilter> filter_ptr( new ImageCollectionGeometricFilter( &sfm_data, regions_provider ) ); if ( filter_ptr ) { system::Timer timer; const double d_distance_ratio = 0.6; PairWiseMatches map_GeometricMatches; switch ( eGeometricModelToCompute ) { case HOMOGRAPHY_MATRIX: { const bool bGeometric_only_guided_matching = true; filter_ptr->Robust_model_estimation( GeometricFilter_HMatrix_AC( 4.0, imax_iteration ), map_PutativeMatches, bGuided_matching, bGeometric_only_guided_matching ? -1.0 : d_distance_ratio, &progress ); map_GeometricMatches = filter_ptr->Get_geometric_matches(); } break; case FUNDAMENTAL_MATRIX: { filter_ptr->Robust_model_estimation( GeometricFilter_FMatrix_AC( 4.0, imax_iteration ), map_PutativeMatches, bGuided_matching, d_distance_ratio, &progress ); map_GeometricMatches = filter_ptr->Get_geometric_matches(); } break; case ESSENTIAL_MATRIX: { filter_ptr->Robust_model_estimation( GeometricFilter_EMatrix_AC( 4.0, imax_iteration ), map_PutativeMatches, bGuided_matching, d_distance_ratio, &progress ); map_GeometricMatches = filter_ptr->Get_geometric_matches(); //-- Perform an additional check to remove pairs with poor overlap std::vector<PairWiseMatches::key_type> vec_toRemove; for ( const auto& pairwisematches_it : map_GeometricMatches ) { const size_t putativePhotometricCount = map_PutativeMatches.find( pairwisematches_it.first )->second.size(); const size_t putativeGeometricCount = pairwisematches_it.second.size(); const float ratio = putativeGeometricCount / static_cast<float>( putativePhotometricCount ); if ( putativeGeometricCount < 50 || ratio < .3f ) { // the pair will be removed vec_toRemove.push_back( pairwisematches_it.first ); } } //-- remove discarded pairs for ( const auto& pair_to_remove_it : vec_toRemove ) { map_GeometricMatches.erase( pair_to_remove_it ); } } break; case ESSENTIAL_MATRIX_ANGULAR: { filter_ptr->Robust_model_estimation( GeometricFilter_ESphericalMatrix_AC_Angular<false>(4.0, imax_iteration), map_PutativeMatches, bGuided_matching, d_distance_ratio, &progress); map_GeometricMatches = filter_ptr->Get_geometric_matches(); } break; case ESSENTIAL_MATRIX_UPRIGHT: { filter_ptr->Robust_model_estimation( GeometricFilter_ESphericalMatrix_AC_Angular<true>(4.0, imax_iteration), map_PutativeMatches, bGuided_matching, d_distance_ratio, &progress); map_GeometricMatches = filter_ptr->Get_geometric_matches(); } break; case ESSENTIAL_MATRIX_ORTHO: { filter_ptr->Robust_model_estimation( GeometricFilter_EOMatrix_RA( 2.0, imax_iteration ), map_PutativeMatches, bGuided_matching, d_distance_ratio, &progress ); map_GeometricMatches = filter_ptr->Get_geometric_matches(); } break; } //--------------------------------------- //-- Export geometric filtered matches //--------------------------------------- if ( !Save( map_GeometricMatches, sFilteredMatchesFilename ) ) { OPENMVG_LOG_ERROR << "Cannot save filtered matches in: " << sFilteredMatchesFilename; return EXIT_FAILURE; } // -- export Geometric View Graph statistics graph::getGraphStatistics(sfm_data.GetViews().size(), getPairs(map_GeometricMatches)); OPENMVG_LOG_INFO << "Task done in (s): " << timer.elapsed(); //-- export Adjacency matrix OPENMVG_LOG_INFO << "\n Export Adjacency Matrix of the pairwise's geometric matches"; PairWiseMatchingToAdjacencyMatrixSVG( sfm_data.GetViews().size(), map_GeometricMatches, stlplus::create_filespec( sMatchesDirectory, "GeometricAdjacencyMatrix", "svg" ) ); const Pair_Set outputPairs = getPairs( map_GeometricMatches ); //-- export view pair graph once geometric filter have been done { std::set<IndexT> set_ViewIds; std::transform( sfm_data.GetViews().begin(), sfm_data.GetViews().end(), std::inserter( set_ViewIds, set_ViewIds.begin() ), stl::RetrieveKey() ); graph::indexedGraph putativeGraph( set_ViewIds, outputPairs ); graph::exportToGraphvizData( stlplus::create_filespec( sMatchesDirectory, "geometric_matches" ), putativeGraph ); } // Write pairs if ( !sOutputPairsFilename.empty() ) { OPENMVG_LOG_INFO << "Saving pairs to: " << sOutputPairsFilename; if ( !savePairs( sOutputPairsFilename, outputPairs ) ) { OPENMVG_LOG_ERROR << "Failed to write pairs file"; return EXIT_FAILURE; } } } return EXIT_SUCCESS; }
16,160
C++
.cpp
376
36.276596
150
0.622015
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,812
main_ComputeMatches.cpp
openMVG_openMVG/src/software/SfM/main_ComputeMatches.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2019 Pierre MOULON, Romuald Perrot. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/graph/graph.hpp" #include "openMVG/graph/graph_stats.hpp" #include "openMVG/matching/indMatch.hpp" #include "openMVG/matching/indMatch_utils.hpp" #include "openMVG/matching/pairwiseAdjacencyDisplay.hpp" #include "openMVG/matching_image_collection/Cascade_Hashing_Matcher_Regions.hpp" #include "openMVG/matching_image_collection/Matcher_Regions.hpp" #include "openMVG/matching_image_collection/Pair_Builder.hpp" #include "openMVG/sfm/pipelines/sfm_features_provider.hpp" #include "openMVG/sfm/pipelines/sfm_preemptive_regions_provider.hpp" #include "openMVG/sfm/pipelines/sfm_regions_provider.hpp" #include "openMVG/sfm/pipelines/sfm_regions_provider_cache.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/stl/stl.hpp" #include "openMVG/system/timer.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cstdlib> #include <iostream> #include <memory> #include <string> using namespace openMVG; using namespace openMVG::matching; using namespace openMVG::sfm; using namespace openMVG::matching_image_collection; /// Compute corresponding features between a series of views: /// - Load view images description (regions: features & descriptors) /// - Compute putative local feature matches (descriptors matching) int main( int argc, char** argv ) { CmdLine cmd; std::string sSfM_Data_Filename; std::string sOutputMatchesFilename = ""; float fDistRatio = 0.8f; std::string sPredefinedPairList = ""; std::string sNearestMatchingMethod = "AUTO"; bool bForce = false; unsigned int ui_max_cache_size = 0; // Pre-emptive matching parameters unsigned int ui_preemptive_feature_count = 200; double preemptive_matching_percentage_threshold = 0.08; //required cmd.add( make_option( 'i', sSfM_Data_Filename, "input_file" ) ); cmd.add( make_option( 'o', sOutputMatchesFilename, "output_file" ) ); cmd.add( make_option( 'p', sPredefinedPairList, "pair_list" ) ); // Options cmd.add( make_option( 'r', fDistRatio, "ratio" ) ); cmd.add( make_option( 'n', sNearestMatchingMethod, "nearest_matching_method" ) ); cmd.add( make_option( 'f', bForce, "force" ) ); cmd.add( make_option( 'c', ui_max_cache_size, "cache_size" ) ); // Pre-emptive matching cmd.add( make_option( 'P', ui_preemptive_feature_count, "preemptive_feature_count") ); try { if ( argc == 1 ) throw std::string( "Invalid command line parameter." ); cmd.process( argc, argv ); } catch ( const std::string& s ) { OPENMVG_LOG_INFO << "Usage: " << argv[ 0 ] << '\n' << "[-i|--input_file] A SfM_Data file\n" << "[-o|--output_file] Output file where computed matches are stored\n" << "[-p|--pair_list] Pairs list file\n" << "\n[Optional]\n" << "[-f|--force] Force to recompute data]\n" << "[-r|--ratio] Distance ratio to discard non meaningful matches\n" << " 0.8: (default).\n" << "[-n|--nearest_matching_method]\n" << " AUTO: auto choice from regions type,\n" << " For Scalar based regions descriptor:\n" << " BRUTEFORCEL2: L2 BruteForce matching,\n" << " HNSWL2: L2 Approximate Matching with Hierarchical Navigable Small World graphs,\n" << " HNSWL1: L1 Approximate Matching with Hierarchical Navigable Small World graphs\n" << " tailored for quantized and histogram based descriptors (e.g uint8 RootSIFT)\n" << " ANNL2: L2 Approximate Nearest Neighbor matching,\n" << " CASCADEHASHINGL2: L2 Cascade Hashing matching.\n" << " FASTCASCADEHASHINGL2: (default)\n" << " L2 Cascade Hashing with precomputed hashed regions\n" << " (faster than CASCADEHASHINGL2 but use more memory).\n" << " For Binary based descriptor:\n" << " BRUTEFORCEHAMMING: BruteForce Hamming matching,\n" << " HNSWHAMMING: Hamming Approximate Matching with Hierarchical Navigable Small World graphs\n" << "[-c|--cache_size]\n" << " Use a regions cache (only cache_size regions will be stored in memory)\n" << " If not used, all regions will be load in memory." << "\n[Pre-emptive matching:]\n" << "[-P|--preemptive_feature_count] <NUMBER> Number of feature used for pre-emptive matching"; OPENMVG_LOG_INFO << s; return EXIT_FAILURE; } OPENMVG_LOG_INFO << " You called : " << "\n" << argv[ 0 ] << "\n" << "--input_file " << sSfM_Data_Filename << "\n" << "--output_file " << sOutputMatchesFilename << "\n" << "--pair_list " << sPredefinedPairList << "\n" << "Optional parameters:" << "\n" << "--force " << bForce << "\n" << "--ratio " << fDistRatio << "\n" << "--nearest_matching_method " << sNearestMatchingMethod << "\n" << "--cache_size " << ((ui_max_cache_size == 0) ? "unlimited" : std::to_string(ui_max_cache_size)) << "\n" << "--preemptive_feature_used/count " << cmd.used('P') << " / " << ui_preemptive_feature_count; if (cmd.used('P')) { OPENMVG_LOG_INFO << "--preemptive_feature_count " << ui_preemptive_feature_count; } if ( sOutputMatchesFilename.empty() ) { OPENMVG_LOG_ERROR << "No output file set."; return EXIT_FAILURE; } // ----------------------------- // . Load SfM_Data Views & intrinsics data // . Compute putative descriptor matches // + Export some statistics // ----------------------------- //--------------------------------------- // Read SfM Scene (image view & intrinsics data) //--------------------------------------- SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS))) { OPENMVG_LOG_ERROR << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read."; return EXIT_FAILURE; } const std::string sMatchesDirectory = stlplus::folder_part( sOutputMatchesFilename ); //--------------------------------------- // Load SfM Scene regions //--------------------------------------- // Init the regions_type from the image describer file (used for image regions extraction) using namespace openMVG::features; const std::string sImage_describer = stlplus::create_filespec(sMatchesDirectory, "image_describer", "json"); std::unique_ptr<Regions> regions_type = Init_region_type_from_file(sImage_describer); if (!regions_type) { OPENMVG_LOG_ERROR << "Invalid: " << sImage_describer << " regions type file."; return EXIT_FAILURE; } //--------------------------------------- // a. Compute putative descriptor matches // - Descriptor matching (according user method choice) // - Keep correspondences only if NearestNeighbor ratio is ok //--------------------------------------- // Load the corresponding view regions std::shared_ptr<Regions_Provider> regions_provider; if (ui_max_cache_size == 0) { // Default regions provider (load & store all regions in memory) regions_provider = std::make_shared<Regions_Provider>(); } else { // Cached regions provider (load & store regions on demand) regions_provider = std::make_shared<Regions_Provider_Cache>(ui_max_cache_size); } // If we use pre-emptive matching, we load less regions: if (ui_preemptive_feature_count > 0 && cmd.used('P')) { regions_provider = std::make_shared<Preemptive_Regions_Provider>(ui_preemptive_feature_count); } // Show the progress on the command line: system::LoggerProgress progress; if (!regions_provider->load(sfm_data, sMatchesDirectory, regions_type, &progress)) { OPENMVG_LOG_ERROR << "Cannot load view regions from: " << sMatchesDirectory << "."; return EXIT_FAILURE; } PairWiseMatches map_PutativeMatches; // Build some alias from SfM_Data Views data: // - List views as a vector of filenames & image sizes std::vector<std::string> vec_fileNames; std::vector<std::pair<size_t, size_t>> vec_imagesSize; { vec_fileNames.reserve(sfm_data.GetViews().size()); vec_imagesSize.reserve(sfm_data.GetViews().size()); for (const auto view_it : sfm_data.GetViews()) { const View * v = view_it.second.get(); vec_fileNames.emplace_back(stlplus::create_filespec(sfm_data.s_root_path, v->s_Img_path)); vec_imagesSize.emplace_back(v->ui_width, v->ui_height); } } OPENMVG_LOG_INFO << " - PUTATIVE MATCHES - "; // If the matches already exists, reload them if ( !bForce && ( stlplus::file_exists( sOutputMatchesFilename ) ) ) { if ( !( Load( map_PutativeMatches, sOutputMatchesFilename ) ) ) { OPENMVG_LOG_ERROR << "Cannot load input matches file"; return EXIT_FAILURE; } OPENMVG_LOG_INFO << "\t PREVIOUS RESULTS LOADED;" << " #pair: " << map_PutativeMatches.size(); } else // Compute the putative matches { // Allocate the right Matcher according the Matching requested method std::unique_ptr<Matcher> collectionMatcher; if ( sNearestMatchingMethod == "AUTO" ) { if ( regions_type->IsScalar() ) { OPENMVG_LOG_INFO << "Using FAST_CASCADE_HASHING_L2 matcher"; collectionMatcher.reset(new Cascade_Hashing_Matcher_Regions(fDistRatio)); } else if (regions_type->IsBinary()) { OPENMVG_LOG_INFO << "Using HNSWHAMMING matcher"; collectionMatcher.reset(new Matcher_Regions(fDistRatio, HNSW_HAMMING)); } } else if (sNearestMatchingMethod == "BRUTEFORCEL2") { OPENMVG_LOG_INFO << "Using BRUTE_FORCE_L2 matcher"; collectionMatcher.reset(new Matcher_Regions(fDistRatio, BRUTE_FORCE_L2)); } else if (sNearestMatchingMethod == "BRUTEFORCEHAMMING") { OPENMVG_LOG_INFO << "Using BRUTE_FORCE_HAMMING matcher"; collectionMatcher.reset(new Matcher_Regions(fDistRatio, BRUTE_FORCE_HAMMING)); } else if (sNearestMatchingMethod == "HNSWL2") { OPENMVG_LOG_INFO << "Using HNSWL2 matcher"; collectionMatcher.reset(new Matcher_Regions(fDistRatio, HNSW_L2)); } if (sNearestMatchingMethod == "HNSWL1") { OPENMVG_LOG_INFO << "Using HNSWL1 matcher"; collectionMatcher.reset(new Matcher_Regions(fDistRatio, HNSW_L1)); } else if (sNearestMatchingMethod == "HNSWHAMMING") { OPENMVG_LOG_INFO << "Using HNSWHAMMING matcher"; collectionMatcher.reset(new Matcher_Regions(fDistRatio, HNSW_HAMMING)); } else if (sNearestMatchingMethod == "ANNL2") { OPENMVG_LOG_INFO << "Using ANN_L2 matcher"; collectionMatcher.reset(new Matcher_Regions(fDistRatio, ANN_L2)); } else if (sNearestMatchingMethod == "CASCADEHASHINGL2") { OPENMVG_LOG_INFO << "Using CASCADE_HASHING_L2 matcher"; collectionMatcher.reset(new Matcher_Regions(fDistRatio, CASCADE_HASHING_L2)); } else if (sNearestMatchingMethod == "FASTCASCADEHASHINGL2") { OPENMVG_LOG_INFO << "Using FAST_CASCADE_HASHING_L2 matcher"; collectionMatcher.reset(new Cascade_Hashing_Matcher_Regions(fDistRatio)); } if (!collectionMatcher) { OPENMVG_LOG_ERROR << "Invalid Nearest Neighbor method: " << sNearestMatchingMethod; return EXIT_FAILURE; } // Perform the matching system::Timer timer; { // From matching mode compute the pair list that have to be matched: Pair_Set pairs; if ( sPredefinedPairList.empty() ) { OPENMVG_LOG_INFO << "No input pair file set. Use exhaustive match by default."; const size_t NImage = sfm_data.GetViews().size(); pairs = exhaustivePairs( NImage ); } else if ( !loadPairs( sfm_data.GetViews().size(), sPredefinedPairList, pairs ) ) { OPENMVG_LOG_ERROR << "Failed to load pairs from file: \"" << sPredefinedPairList << "\""; return EXIT_FAILURE; } OPENMVG_LOG_INFO << "Running matching on #pairs: " << pairs.size(); // Photometric matching of putative pairs collectionMatcher->Match( regions_provider, pairs, map_PutativeMatches, &progress ); if (cmd.used('P')) // Preemptive filter { // Keep putative matches only if there is more than X matches PairWiseMatches map_filtered_matches; for (const auto & pairwisematches_it : map_PutativeMatches) { const size_t putative_match_count = pairwisematches_it.second.size(); const int match_count_threshold = preemptive_matching_percentage_threshold * ui_preemptive_feature_count; // TODO: Add an option to keeping X Best pairs if (putative_match_count >= match_count_threshold) { // the pair will be kept map_filtered_matches.insert(pairwisematches_it); } } map_PutativeMatches.clear(); std::swap(map_filtered_matches, map_PutativeMatches); } //--------------------------------------- //-- Export putative matches & pairs //--------------------------------------- if ( !Save( map_PutativeMatches, std::string( sOutputMatchesFilename ) ) ) { OPENMVG_LOG_ERROR << "Cannot save computed matches in: " << sOutputMatchesFilename; return EXIT_FAILURE; } // Save pairs const std::string sOutputPairFilename = stlplus::create_filespec( sMatchesDirectory, "preemptive_pairs", "txt" ); if (!savePairs( sOutputPairFilename, getPairs(map_PutativeMatches))) { OPENMVG_LOG_ERROR << "Cannot save computed matches pairs in: " << sOutputPairFilename; return EXIT_FAILURE; } } OPENMVG_LOG_INFO << "Task (Regions Matching) done in (s): " << timer.elapsed(); } OPENMVG_LOG_INFO << "#Putative pairs: " << map_PutativeMatches.size(); // -- export Putative View Graph statistics graph::getGraphStatistics(sfm_data.GetViews().size(), getPairs(map_PutativeMatches)); //-- export putative matches Adjacency matrix PairWiseMatchingToAdjacencyMatrixSVG( vec_fileNames.size(), map_PutativeMatches, stlplus::create_filespec( sMatchesDirectory, "PutativeAdjacencyMatrix", "svg" ) ); //-- export view pair graph once putative graph matches has been computed { std::set<IndexT> set_ViewIds; std::transform( sfm_data.GetViews().begin(), sfm_data.GetViews().end(), std::inserter( set_ViewIds, set_ViewIds.begin() ), stl::RetrieveKey() ); graph::indexedGraph putativeGraph( set_ViewIds, getPairs( map_PutativeMatches ) ); graph::exportToGraphvizData( stlplus::create_filespec( sMatchesDirectory, "putative_matches" ), putativeGraph ); } return EXIT_SUCCESS; }
15,254
C++
.cpp
354
37.511299
148
0.645706
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,816
main_ConvertMatches.cpp
openMVG_openMVG/src/software/SfM/main_ConvertMatches.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2013, 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/matching/indMatch.hpp" #include "openMVG/matching/indMatch_utils.hpp" #include "third_party/cmdLine/cmdLine.h" #include <cstdlib> #include <string> using namespace openMVG; using namespace openMVG::matching; int main(int argc, char ** argv) { CmdLine cmd; std::string sMatchFile; std::string sOutMatchFile; cmd.add( make_option('m', sMatchFile, "matchfile") ); cmd.add( make_option('o', sOutMatchFile, "outmatchfile") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Convert matches from bin to txt or txt to bin.\nUsage: " << argv[0] << "\n" << "[-m|--sMatchFile filename]\n" << "[-o|--outmatchfile filename]\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } if (sMatchFile.empty()) { std::cerr << "\nmatchfile cannot be an empty option" << std::endl; return EXIT_FAILURE; } if (sOutMatchFile.empty()) { std::cerr << "\noutmatchfile cannot be an empty option" << std::endl; return EXIT_FAILURE; } // Read the matches matching::PairWiseMatches pairWise_matches; if (!Load(pairWise_matches, sMatchFile)) { std::cerr << "\nInvalid matches file." << std::endl; return EXIT_FAILURE; } // Write the matches if (!Save(pairWise_matches, sOutMatchFile)) { std::cerr << "Cannot save matches to: " << sOutMatchFile; return EXIT_FAILURE; } return EXIT_SUCCESS; }
1,872
C++
.cpp
54
30.833333
95
0.671658
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,820
main_evalQuality.cpp
openMVG_openMVG/src/software/SfM/main_evalQuality.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2013, 2014, 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/system/logger.hpp" #include "openMVG/stl/stlMap.hpp" #include "software/SfM/tools_precisionEvaluationToGt.hpp" #include "software/SfM/SfMPlyHelper.hpp" #include "software/SfM/import/io_readGTStrecha.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/htmlDoc/htmlDoc.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cereal/archives/json.hpp> #include <cereal/types/vector.hpp> #include <cstdlib> using namespace openMVG; using namespace openMVG::sfm; using namespace openMVG::cameras; int main(int argc, char **argv) { CmdLine cmd; std::string sGTPath, sComputedSfmDataFilePath, sOutDir = ""; cmd.add( make_option('i', sGTPath, "gt") ); cmd.add( make_option('c', sComputedSfmDataFilePath, "computed") ); cmd.add( make_option('o', sOutDir, "outdir") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { OPENMVG_LOG_INFO << "Usage: " << argv[0] << '\n' << "[-i|--gt] path (where the ground truth dataset is saved (i.e sfm_data.bin/json/xml).\n" << "[-c|--computed] path to the sfm_data file to compare (i.e sfm_data.bin/json/xml).\n" << "[-o|--output] path (where the registration statistics will be saved).\n"; OPENMVG_LOG_ERROR << s; return EXIT_FAILURE; } if (sOutDir.empty()) { OPENMVG_LOG_ERROR << "\nIt is an invalid output directory"; return EXIT_FAILURE; } if (!stlplus::folder_exists(sOutDir)) stlplus::folder_create(sOutDir); //--------------------------------------- // Quality evaluation //--------------------------------------- // 1. Initialize the GT: // SfM_Data sfm_data_gt; { if (stlplus::is_file(sGTPath)) { if (!Load(sfm_data_gt, sGTPath, ESfM_Data(VIEWS|EXTRINSICS))) { OPENMVG_LOG_ERROR << "The input GT path file \""<< sGTPath << "\" cannot be read."; return EXIT_FAILURE; } } else // Compatibility with previous configuration (Strecha dataset) { if (stlplus::is_folder(sGTPath)) { SfM_Data_GT_Loader_Strecha sfm_data_gt_loader; if (!sfm_data_gt_loader.run( stlplus::folder_append_separator(sGTPath) + "gt_dense_cameras", stlplus::folder_append_separator(sGTPath) + "images")) { OPENMVG_LOG_ERROR << "The input GT path directory \""<< sGTPath << "\" cannot be read."; return EXIT_FAILURE; } sfm_data_gt = sfm_data_gt_loader.GetSfMData(); } else { OPENMVG_LOG_ERROR << "Cannot read GT: "<< sGTPath; return EXIT_FAILURE; } } } // 2. Load the scene to compare // SfM_Data sfm_data_to_compare; { if (!Load(sfm_data_to_compare, sComputedSfmDataFilePath, ESfM_Data(VIEWS|EXTRINSICS))) { OPENMVG_LOG_ERROR << "The input SfM_Data file \""<< sComputedSfmDataFilePath << "\" cannot be read."; return EXIT_FAILURE; } } // Check if GT and loaded scene have the same camera count if (sfm_data_gt.GetPoses().size() != sfm_data_to_compare.GetPoses().size()) { OPENMVG_LOG_WARNING << "Dataset poses count does not match." << "\n" << "#GT poses: " << sfm_data_gt.GetPoses().size() << "\n" << "#Scene poses: " << sfm_data_to_compare.GetPoses().size(); } // Collect corresponding poses ids std::vector<IndexT> pose_id_intersection; { // Collect GT pose_ids. std::set<IndexT> pose_id_gt; std::transform( sfm_data_gt.GetPoses().cbegin(), sfm_data_gt.GetPoses().cend(), std::inserter(pose_id_gt, pose_id_gt.begin()), stl::RetrieveKey()); // Collect the sfm_data to compare pose_ids. std::set<IndexT> pose_id_to_compare; std::transform( sfm_data_to_compare.GetPoses().cbegin(), sfm_data_to_compare.GetPoses().cend(), std::inserter(pose_id_to_compare, pose_id_to_compare.begin()), stl::RetrieveKey()); // Check if the pose_id intersect or not std::set_intersection(pose_id_gt.cbegin(), pose_id_gt.cend(), pose_id_to_compare.cbegin(), pose_id_to_compare.cend(), std::back_inserter(pose_id_intersection)); if (pose_id_intersection.size() != sfm_data_gt.GetPoses().size()) { OPENMVG_LOG_WARNING << "The datasets' poses id count does not match."; } } if (pose_id_intersection.empty()) { OPENMVG_LOG_WARNING << "No common poses Id found."; } // 3. Find corresponding camera pose data: // std::vector<Vec3> camera_pos_gt, camera_pos_to_compare; std::vector<Mat3> camera_rot_gt, camera_rot_to_compare; for (const auto & pose_id : pose_id_intersection) { const auto & pose_to_compare_it = sfm_data_to_compare.GetPoses().at(pose_id); const auto & pose_gt_it = sfm_data_gt.GetPoses().at(pose_id); camera_pos_gt.push_back(pose_gt_it.center()); camera_rot_gt.push_back(pose_gt_it.rotation()); camera_pos_to_compare.push_back(pose_to_compare_it.center()); camera_rot_to_compare.push_back(pose_to_compare_it.rotation()); } // Visual output of the camera location plyHelper::exportToPly(camera_pos_gt, (stlplus::folder_append_separator(sOutDir) + "camGT.ply").c_str()); plyHelper::exportToPly(camera_pos_to_compare, (stlplus::folder_append_separator(sOutDir) + "camComputed.ply").c_str()); // Evaluation htmlDocument::htmlDocumentStream _htmlDocStream("openMVG Quality evaluation."); std::vector<double> vec_distance_residuals, vec_rotation_angular_residuals; EvaluateToGT(camera_pos_gt, camera_pos_to_compare, camera_rot_gt, camera_rot_to_compare, sOutDir, &_htmlDocStream, vec_distance_residuals, vec_rotation_angular_residuals); std::ofstream htmlFileStream((stlplus::folder_append_separator(sOutDir) + "ExternalCalib_Report.html").c_str()); htmlFileStream << _htmlDocStream.getDoc(); // Export a JSON blob with all the statistics: const std::string out_json_filename = stlplus::create_filespec(sOutDir, "gt_eval_stats_blob", "json"); std::ofstream os(out_json_filename); if (os) { cereal::JSONOutputArchive ar( os ); ar << cereal::make_nvp("gt_dataset", sGTPath) << cereal::make_nvp("eval_dataset", sComputedSfmDataFilePath) << cereal::make_nvp("gt_num_poses", sfm_data_gt.GetPoses().size()) << cereal::make_nvp("eval_num_poses", sfm_data_to_compare.GetPoses().size()) << cereal::make_nvp("distance_residuals", vec_distance_residuals) << cereal::make_nvp("rotation_angular_residuals", vec_rotation_angular_residuals); } else { OPENMVG_LOG_ERROR << "Cannot export JSON stats blob output: " << out_json_filename; return EXIT_FAILURE; } return EXIT_SUCCESS; }
7,204
C++
.cpp
178
35.544944
107
0.661136
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,821
main_ComputeVLAD.cpp
openMVG_openMVG/src/software/SfM/main_ComputeVLAD.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2019 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/graph/graph.hpp" #include "openMVG/graph/graph_stats.hpp" #include "openMVG/matching/indMatch_utils.hpp" #include "openMVG/matching/matcher_brute_force.hpp" #include "openMVG/matching/pairwiseAdjacencyDisplay.hpp" #include "openMVG/matching_image_collection/Pair_Builder.hpp" #include "openMVG/matching_image_collection/Retrieval_Helpers.hpp" #include "openMVG/matching_image_collection/Vlad.hpp" #include "openMVG/sfm/pipelines/sfm_preemptive_regions_provider.hpp" #include "openMVG/sfm/pipelines/sfm_regions_provider_cache.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/stl/stl.hpp" #include "openMVG/system/loggerprogress.hpp" #include "openMVG/system/timer.hpp" #include "openMVG/vector_graphics/svgDrawer.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cstdlib> #include <iostream> #include <string> #ifdef OPENMVG_USE_OPENMP #include <omp.h> #endif using namespace openMVG; using namespace openMVG::matching; using namespace openMVG::sfm; using namespace openMVG::retrieval; using namespace svg; // TODO: these two output function could be factored and put somewhere else // Display the image retrieval matrix template <typename Order> void saveRetrievalMatrix( const std::string &filename, const SfM_Data &sfm_data, const IndexedPairwiseSimilarity<Order> &result_ordered_by_similarity) { const size_t num_neighbors = result_ordered_by_similarity.begin()->second.size(); const int size = 1024; svgDrawer svg_stream(size * num_neighbors + 1, size * result_ordered_by_similarity.size()); int x_offset = 0; int y_offset = 0; for (const auto result_it : result_ordered_by_similarity) { const auto ref_view_id = result_it.first; const auto ref_view = sfm_data.GetViews().at(ref_view_id); const std::string ref_view_filename = stlplus::create_filespec(sfm_data.s_root_path, ref_view->s_Img_path); svg_stream << svg::drawImage(ref_view_filename, size, size, x_offset * size, y_offset * size); const auto &retrieval_list = result_it.second; for (const auto retrieval_list_it : retrieval_list) { ++x_offset; const auto found_view_id = retrieval_list_it.second; const auto found_view = sfm_data.GetViews().at(found_view_id); const std::string found_view_filename = stlplus::create_filespec( sfm_data.s_root_path, found_view->s_Img_path); svg_stream << svg::drawImage(found_view_filename, size, size, x_offset * size, y_offset * size); } x_offset = 0; ++y_offset; } std::ofstream svg_file(filename.c_str()); svg_file << svg_stream.closeSvgFile().str(); svg_file.close(); } void saveAdjacencyMatrixViewGraph(const Pair_Set &resulting_pairs, const SfM_Data &sfm_data, const std::string &base_folder) { PairWiseMatches vlad_pairwise_matches; for (const auto pair_it : resulting_pairs) { vlad_pairwise_matches[pair_it] = { 0}; // Set at last a match to be displayed } PairWiseMatchingToAdjacencyMatrixSVG( sfm_data.GetViews().size(), vlad_pairwise_matches, stlplus::create_filespec(base_folder, "PutativeAdjacencyMatrixRetrieval", "svg")); //-- export view pair graph once putative graph matches have been computed { std::set<IndexT> set_viewIds; std::transform(sfm_data.GetViews().begin(), sfm_data.GetViews().end(), std::inserter(set_viewIds, set_viewIds.begin()), stl::RetrieveKey()); graph::indexedGraph putative_graph(set_viewIds, resulting_pairs); graph::exportToGraphvizData( stlplus::create_filespec(base_folder, "retrieval_pairs"), putative_graph); } } #include <Eigen/Dense> #include <cereal/archives/binary.hpp> #include <cereal/cereal.hpp> #include <cereal/types/vector.hpp> #include <fstream> namespace cereal { template <class Archive, class Derived> inline typename std::enable_if< traits::is_output_serializable<BinaryData<typename Derived::Scalar>, Archive>::value, void>::type save(Archive &ar, Eigen::PlainObjectBase<Derived> const &m) { typedef Eigen::PlainObjectBase<Derived> ArrT; if (ArrT::RowsAtCompileTime == Eigen::Dynamic) ar(m.rows()); if (ArrT::ColsAtCompileTime == Eigen::Dynamic) ar(m.cols()); ar(binary_data(m.data(), m.size() * sizeof(typename Derived::Scalar))); } template <class Archive, class Derived> inline typename std::enable_if< traits::is_input_serializable<BinaryData<typename Derived::Scalar>, Archive>::value, void>::type load(Archive &ar, Eigen::PlainObjectBase<Derived> &m) { typedef Eigen::PlainObjectBase<Derived> ArrT; Eigen::Index rows = ArrT::RowsAtCompileTime, cols = ArrT::ColsAtCompileTime; if (rows == Eigen::Dynamic) ar(rows); if (cols == Eigen::Dynamic) ar(cols); m.resize(rows, cols); ar(binary_data(m.data(), static_cast<std::size_t>(rows * cols * sizeof(typename Derived::Scalar)))); } } // namespace cereal int main(int argc, char **argv) { CmdLine cmd; std::string sSfM_Data_Filename; std::string sMatchesDirectory = ""; std::string sPairFile = "vlad_pairs.txt"; int32_t num_neighbors = 0; int32_t codebook_size = 128; int32_t vlad_flavor = static_cast<int>(VLAD_NORMALIZATION::RESIDUAL_NORMALIZATION_PWR_LAW); int32_t max_feats = -1; uint32_t ui_max_cache_size = 0; // required cmd.add(make_option('i', sSfM_Data_Filename, "input_file")); cmd.add(make_option('o', sMatchesDirectory, "out_dir")); // optional cmd.add(make_option('n', num_neighbors, "num_neighbors")); cmd.add(make_option('d', codebook_size, "codebook_size")); cmd.add(make_option('p', sPairFile, "pair_file")); cmd.add(make_option('v', vlad_flavor, "vlad_flavor")); cmd.add(make_option('c', ui_max_cache_size, "cache_size")); cmd.add(make_option('m', max_feats, "max_feats")); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string &s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_file] a SfM_Data file\n" << "[-o|--out_dir path] output path where computed features are " "stored\n" << "[-p|--pair_file] name of the output pair file (def. " "vlad_pairs.txt)\n" << "[-n|--num_neighbors] num neighbors per image (<= 0: auto i.e. 30% " "of the whole set)\n" << "[-d|--codebook_size] size of the codebook (number of kmeans " "centroids) used to compute descriptor (default=128)\n" << "[-v|--vlad_flavor] VLAD flavor (default=" << vlad_flavor << "):\n" << "\t" << static_cast<int>(VLAD_NORMALIZATION::SIGNED_SQUARE_ROOTING) << ": \"Aggregating local descriptors into compact codes\". H. Jegou " "et al. PAMI 2012\n" << "\t" << static_cast<int>(VLAD_NORMALIZATION::INTRA_NORMALIZATION) << ": \"All About VLAD\". R. Arandjelovic and A. Zisserman. CVPR 2013\n" << "\t" << static_cast<int>(VLAD_NORMALIZATION::RESIDUAL_NORMALIZATION_PWR_LAW) << ": \"Revisiting the VLAD image representation\". J. Delhumeau et " "al. ACM Multimedia 2013. \n" << "[-m|--max_feats] Max number of features to perform the learning " "step (<= 0: whole feature set is used, default=" << max_feats << ")\n" << "[-c|--cache_size] Use a regions cache (only cache_size regions " "will be stored in memory)\n" << "\t" << "If not used, all regions will be loaded in memory." << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } std::cout << " You called : " << "\n" << argv[0] << "\n" << "--input_file " << sSfM_Data_Filename << "\n" << "--out_dir " << sMatchesDirectory << "\n" << "--pair_file " << sPairFile << "\n" << "--num_neighbors " << num_neighbors << "\n" << "--codebook_size " << codebook_size << "\n" << "--vlad_flavor " << vlad_flavor << "\n" << "--max_feats " << max_feats << "\n" << std::endl; if (sMatchesDirectory.empty() || !stlplus::is_folder(sMatchesDirectory)) { std::cerr << "\nIt is an invalid output directory" << std::endl; return EXIT_FAILURE; } //--------------------------------------- // Read SfM Scene (image view & intrinsics data) //--------------------------------------- SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS | INTRINSICS))) { std::cerr << std::endl << "The input SfM_Data file \"" << sSfM_Data_Filename << "\" cannot be read." << std::endl; return EXIT_FAILURE; } //--------------------------------------- // Load SfM Scene regions //--------------------------------------- // Init the regions_type from the image describer file (used for image regions // extraction) using namespace openMVG::features; const std::string sImage_describer = stlplus::create_filespec(sMatchesDirectory, "image_describer", "json"); std::unique_ptr<Regions> regions_type = Init_region_type_from_file(sImage_describer); if (!regions_type) { std::cerr << "Invalid: " << sImage_describer << " regions type file." << std::endl; return EXIT_FAILURE; } // Load the corresponding view regions - for learning - std::shared_ptr<Regions_Provider> learning_regions_provider; if (max_feats <= 0) { if (ui_max_cache_size == 0) { // Default regions provider (load & store all regions in memory) learning_regions_provider = std::make_shared<Regions_Provider>(); } else { // cached region provider (progressive loading) learning_regions_provider = std::make_shared<Regions_Provider_Cache>(ui_max_cache_size); } } else { learning_regions_provider = std::make_shared<Preemptive_Regions_Provider>( max_feats / sfm_data.GetViews().size()); } system::LoggerProgress progress; if (!learning_regions_provider->load(sfm_data, sMatchesDirectory, regions_type, &progress)) { std::cerr << std::endl << "Invalid regions." << std::endl; return EXIT_FAILURE; } // Default parameters for num_neighbors if (num_neighbors <= 0) { num_neighbors = static_cast<int>(std::ceil(sfm_data.views.size() * 0.3)); } if (num_neighbors > sfm_data.views.size()) { num_neighbors = sfm_data.views.size() - 1; } const VLAD_NORMALIZATION vlad_normalization = static_cast<VLAD_NORMALIZATION>(vlad_flavor); const size_t base_descriptor_length = learning_regions_provider->getRegionsType()->DescriptorLength(); const size_t vlad_descriptor_length = base_descriptor_length * codebook_size; // ----------------------------- // VLAD Computation // Learn the codebook: compute K centroids // Embedding: compute descriptors to centroid ids // Aggregation: Sum descriptor-to-centroid distances // Normalization: Each VLAD flavor come with different schemes of // normalization (mainly to handle visual bursts) // ----------------------------- system::Timer timer; std::unique_ptr<VLADBase> vlad_builder; if (dynamic_cast<const SIFT_Regions*>(regions_type.get())){ OPENMVG_LOG_INFO << "SIFT"; vlad_builder.reset(new VLAD<SIFT_Regions>); } else if (dynamic_cast<const AKAZE_Float_Regions*>(regions_type.get())) { OPENMVG_LOG_INFO << "AKAZE"; vlad_builder.reset(new VLAD<AKAZE_Float_Regions>); } else { OPENMVG_LOG_ERROR << "VLAD does not support this Regions type."; OPENMVG_LOG_ERROR << "Please consider add the specialization here."; return EXIT_FAILURE; } std::vector<IndexT> view_ids; for (const auto &view : sfm_data.GetViews()) { const auto &view_id = view.first; view_ids.push_back(view_id); } // Convert input regions to array VLADBase::DescriptorVector descriptor_array = vlad_builder->RegionsToCodebook( view_ids, learning_regions_provider); std::cout << "Using # features for learning: " << descriptor_array.size() << std::endl; VLADBase::DescriptorVector codebook; codebook = vlad_builder->BuildCodebook(descriptor_array, codebook_size); // Freeing some memory descriptor_array.clear(); descriptor_array.shrink_to_fit(); std::unique_ptr<features::Regions> codebook_regions(regions_type->EmptyClone()); vlad_builder->CodebookToRegions(codebook_regions, codebook); std::shared_ptr<Regions_Provider> embedding_regions_provider; if (max_feats <= 0) { embedding_regions_provider = std::move(learning_regions_provider); } else { // cached region provider (progressive loading) if (ui_max_cache_size == 0) { embedding_regions_provider = std::make_shared<Regions_Provider>(); } else { embedding_regions_provider = std::make_shared<Regions_Provider_Cache>(ui_max_cache_size); } if (!embedding_regions_provider->load(sfm_data, sMatchesDirectory, regions_type, &progress)) { std::cerr << std::endl << "Invalid regions." << std::endl; return EXIT_FAILURE; } } VLADBase::VladMatrixType vlad_image_descriptors = vlad_builder->ComputeVLADEmbedding( view_ids, codebook_regions, embedding_regions_provider); // release the region provider embedding_regions_provider.reset(); // Data structures to store the Results Pair_Set resulting_pairs; using DescendingIndexedPairwiseSimilarity = IndexedPairwiseSimilarity<std::greater<double>>; DescendingIndexedPairwiseSimilarity result_ordered_by_similarity; // // Retrieval // progress.Restart( sfm_data.GetViews().size(), "- VLAD Retrieval... -"); #ifdef OPENMVG_USE_OPENMP #pragma omp parallel #endif for (int i = 0; i < sfm_data.GetViews().size(); i++) { const auto &view_id = sfm_data.GetViews().at(i)->id_view; const VLADBase::VladInternalType *query = vlad_image_descriptors.col(view_id).data(); matching::ArrayMatcherBruteForce<VLADBase::VladInternalType, matching::LInner<VLADBase::VladInternalType>> matcher; if (!matcher.Build(vlad_image_descriptors.data(), sfm_data.views.size(), vlad_descriptor_length)) { std::cout << "Error::Build" << std::endl; } const size_t NN = num_neighbors + 1; // num_neighbors + 1 (the query vector // itself is part of the database) IndMatches nearest_neighbor_ids; std::vector<VLADBase::VladInternalType> nearest_neighbor_similarities; if (!matcher.SearchNeighbours(query, 1, &nearest_neighbor_ids, &nearest_neighbor_similarities, NN)) std::cout << "Error::SearchNeighbours" << std::endl; #ifdef OPENMVG_USE_OPENMP #pragma omp single nowait #endif { #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { for (int id = 0; id < nearest_neighbor_ids.size(); ++id) { const auto pair = nearest_neighbor_ids[id]; if (view_id == pair.j_) continue; // Ignore if we find the same image const auto similarity = -1. * nearest_neighbor_similarities[id]; resulting_pairs.insert( {std::min(view_id, pair.j_), std::max(view_id, pair.j_)}); result_ordered_by_similarity[view_id].insert({similarity, pair.j_}); } ++progress; } } } OPENMVG_LOG_INFO << "Task done in (s): " << timer.elapsed(); // -- export Putative View Graph statistics graph::getGraphStatistics(sfm_data.GetViews().size(), resulting_pairs); // Export pairs into a text file savePairs(sPairFile, resulting_pairs); saveAdjacencyMatrixViewGraph(resulting_pairs, sfm_data, sMatchesDirectory); // Export the retrieval matrix saveRetrievalMatrix( stlplus::create_filespec(sMatchesDirectory, "retrieval_matches_matrix.svg"), sfm_data, result_ordered_by_similarity); // Export the sim file std::string sSimFile = stlplus::create_filespec( stlplus::folder_part(sPairFile), stlplus::create_filename(stlplus::basename_part(sPairFile) + "_simscores", ".txt")); savePairwiseSimilarityScores(sSimFile, result_ordered_by_similarity); return EXIT_SUCCESS; }
16,950
C++
.cpp
389
37.59126
93
0.653776
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,822
main_SfMInit_ImageListingFromKnownPoses.cpp
openMVG_openMVG/src/software/SfM/import/main_SfMInit_ImageListingFromKnownPoses.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2018 Yan Qingsong, Pierre Moulon. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/cameras/cameras.hpp" #include "openMVG/cameras/PinholeCamera.hpp" #include "openMVG/geometry/pose3.hpp" #include "openMVG/exif/exif_IO_EasyExif.hpp" #include "openMVG/exif/sensor_width_database/ParseDatabase.hpp" #include "openMVG/geodesy/geodesy.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/numeric/eigen_alias_definition.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/sfm/sfm_data_utils.hpp" #include "openMVG/sfm/sfm_view.hpp" #include "openMVG/sfm/sfm_view_priors.hpp" #include "openMVG/system/logger.hpp" #include "openMVG/types.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <fstream> #include <memory> #include <string> #include <utility> #include "io_readGTMultiface.hpp" #include "io_readGTBlendedMVS.hpp" #include "io_readGTDTUMVS.hpp" #include "io_readGTETH3D.hpp" #include "io_readGTKitti.hpp" #include "io_readGTMiddleBury.hpp" #include "io_readGTStrecha.hpp" using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::exif; using namespace openMVG::geodesy; using namespace openMVG::image; using namespace openMVG::sfm; // // Create the description of an input image dataset for OpenMVG toolsuite // - Export a SfM_Data file with View & Intrinsic data // int main(int argc, char **argv) { CmdLine cmd; std::string sImageDir, sGroundTruthDir, sOutputDir = ""; int ground_truth_Dataset = 0; cmd.add( make_option('i', sImageDir, "imageDirectory") ); cmd.add( make_option('g', sGroundTruthDir, "groundTruthDirectory") ); cmd.add( make_option('t', ground_truth_Dataset, "groundTruthDataset")); cmd.add( make_option('o', sOutputDir, "outputDirectory") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { OPENMVG_LOG_INFO << "Usage: " << argv[0] << '\n' << "[-i|--imageDirectory]\n" << "[-g|--groundTruthDirectory]\n" << "[-t]--groundTruthDataset]\n" << "\t 1: Strecha's Dataset\n" << "\t 2: MiddleBury's Dataset\n" << "\t 3: DTU MVS Dataset\n" << "\t 4: ETH 3D Dataset\n" << "\t 5: Kitti Odometry Dataset\n" << "\t 6: BlendedMVS Dataset\n" << "\t 7: Multiface Dataset\n" << "[-o|--outputDirectory]\n"; OPENMVG_LOG_ERROR << s; return EXIT_FAILURE; } OPENMVG_LOG_INFO << " You called : \n" << argv[0] << "\n" << "--imageDirectory " << sImageDir << "\n" << "--groundTruthDirectory " << sGroundTruthDir << "\n" << "--groundTruthDataset " << ground_truth_Dataset << "\n" << "--outputDirectory " << sOutputDir; if ( !stlplus::folder_exists( sImageDir ) ) { OPENMVG_LOG_ERROR << "\nThe input directory doesn't exist"; return EXIT_FAILURE; } if ( !stlplus::folder_exists( sGroundTruthDir ) ) { OPENMVG_LOG_ERROR << "\nThe input ground truth directory doesn't exist"; return EXIT_FAILURE; } if (sOutputDir.empty()) { OPENMVG_LOG_ERROR << "\nInvalid output directory"; return EXIT_FAILURE; } if ( !stlplus::folder_exists( sOutputDir ) ) { if ( !stlplus::folder_create( sOutputDir )) { OPENMVG_LOG_ERROR << "\nCannot create output directory"; return EXIT_FAILURE; } } // Configure an empty scene with Views and their corresponding cameras std::shared_ptr<SfM_Data_GT_Loader_Interface> sfm_data_gt; switch(ground_truth_Dataset) { case 1: sfm_data_gt = std::make_shared<SfM_Data_GT_Loader_Strecha>(); break; case 2: sfm_data_gt = std::make_shared<SfM_Data_GT_Loader_MiddleBury>(); break; case 3: sfm_data_gt = std::make_shared<SfM_Data_GT_Loader_DTU_MVS>(); break; case 4: sfm_data_gt = std::make_shared<SfM_Data_GT_Loader_ETH_3D>(); break; case 5: sfm_data_gt = std::make_shared<SfM_Data_GT_Loader_Kitti>(); break; case 6: sfm_data_gt = std::make_shared<SfM_Data_GT_Loader_BlendedMVS>(); break; case 7: sfm_data_gt = std::make_shared<SfM_Data_GT_Loader_Multiface>(); break; default: OPENMVG_LOG_ERROR << "Error: Not Support Dataset"; return EXIT_FAILURE; } // Load the gt data if (!sfm_data_gt->run(sGroundTruthDir, sImageDir)) { return EXIT_FAILURE; } // Store SfM_Data views & intrinsic data if (!Save( sfm_data_gt->GetSfMData(), stlplus::create_filespec( sOutputDir, "sfm_data.json" ).c_str(), ESfM_Data(ALL))) { return EXIT_FAILURE; } OPENMVG_LOG_INFO << "\nSfMInit_ImageListing report:\n" << "listed #File(s): " << sfm_data_gt->GetImageNumber() << "\n" << "usable #File(s) listed in sfm_data: " << sfm_data_gt->GetSfMData().GetViews().size() << "\n" << "usable #Pose(s) listed in sfm_data: " << sfm_data_gt->GetSfMData().GetPoses().size() << "\n" << "usable #Intrinsic(s) listed in sfm_data: " << sfm_data_gt->GetSfMData().GetIntrinsics().size(); return EXIT_SUCCESS; }
5,447
C++
.cpp
154
31.285714
103
0.669324
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,833
main_ExportCameraFrustums.cpp
openMVG_openMVG/src/software/SfM/export/main_ExportCameraFrustums.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/geometry/frustum.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_filters_frustum.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/system/logger.hpp" #include "openMVG/system/timer.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cstdlib> #include <string> using namespace openMVG; using namespace openMVG::sfm; /// Export camera frustrums as a triangle PLY file int main(int argc, char **argv) { OPENMVG_LOG_INFO << "Export camera frustums"; CmdLine cmd; std::string sSfM_Data_Filename; std::string sOutFile = ""; double z_near = -1.; double z_far = -1.; cmd.add( make_option('i', sSfM_Data_Filename, "input_file") ); cmd.add( make_option('o', sOutFile, "output_file") ); cmd.add( make_option('n', z_near, "z_near") ); cmd.add( make_option('f', z_far, "z_far") ); cmd.add( make_switch('c', "colorize") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_file] path to a SfM_Data scene\n" << "[-o|--output_file] PLY file to store the camera frustums as triangle meshes.\n" << "[-n|--z_near] 'optional' distance of the near camera plane\n" << "[-f|--z_far] 'optional' distance of the far camera plane\n" << "[-c|--colorize] 'optional' colorize the camera frustums.\n" << std::endl; OPENMVG_LOG_ERROR << s; return EXIT_FAILURE; } // Load input SfM_Data scene SfM_Data sfm_data; if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS))) { OPENMVG_LOG_ERROR << "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read."; return EXIT_FAILURE; } // Assert that we can create the output directory/file if (!stlplus::folder_exists( stlplus::folder_part(sOutFile) )) if (!stlplus::folder_create( stlplus::folder_part(sOutFile) )) return EXIT_FAILURE; // Detect if colorization is requested const bool colorize = cmd.used('c'); // If sfm_data have not structure, cameras are displayed as tiny normalized cones const Frustum_Filter frustum_filter(sfm_data, z_near, z_far); if (!sOutFile.empty()) { if (frustum_filter.export_Ply(sOutFile, colorize)) return EXIT_SUCCESS; } return EXIT_FAILURE; }
2,754
C++
.cpp
66
38.545455
99
0.691617
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,834
main_openMVGSpherical2Cubic.cpp
openMVG_openMVG/src/software/SfM/export/main_openMVGSpherical2Cubic.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2019 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/geometry/pose3.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/numeric/eigen_alias_definition.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/sfm/sfm_landmark.hpp" #include "openMVG/sfm/sfm_view.hpp" #include "openMVG/spherical/cubic_image_sampler.hpp" #include "openMVG/system/loggerprogress.hpp" #include "openMVG/types.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <array> #include <cstdlib> #include <cmath> #include <iomanip> using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::sfm; int main(int argc, char *argv[]) { CmdLine cmd; std::string s_sfm_data_filename; std::string s_out_dir = ""; int force_recompute_images = 1; int size_cubic_images = 1024; cmd.add( make_option('i', s_sfm_data_filename, "sfmdata") ); cmd.add( make_option('o', s_out_dir, "outdir") ); cmd.add( make_option('f', force_recompute_images, "force_compute_cubic_images") ); cmd.add( make_option('s', size_cubic_images, "size-cubic-images") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--sfmdata] filename, the SfM_Data file to convert\n" << "[-o|--outdir path]\n" << "[-f|--force_recompute_images] (default 1)\n" << "[-s|--size-cubic-images] (default 1024) pixel size of the resulting cubic images, " << "non-positive values will automatically scale the output based on the input" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } OPENMVG_LOG_INFO << "force_recompute_images = " << force_recompute_images; std::cout << "size_cubic_images = "; if(size_cubic_images > 0) std::cout << size_cubic_images << std::endl; else std::cout << "auto" << std::endl; // Create output dir if (!stlplus::folder_exists(s_out_dir)) stlplus::folder_create(s_out_dir); SfM_Data sfm_data; if (!Load(sfm_data, s_sfm_data_filename, ESfM_Data(ALL))) { OPENMVG_LOG_ERROR << "The input SfM_Data file \"" << s_sfm_data_filename << "\" cannot be read."; return EXIT_FAILURE; } SfM_Data sfm_data_out; // the sfm_data that stores the cubical image list sfm_data_out.s_root_path = s_out_dir; // Convert every spherical view to cubic views { system::LoggerProgress my_progress_bar( sfm_data.GetViews().size(), "Generating cubic views:"); const Views & views = sfm_data.GetViews(); const Poses & poses = sfm_data.GetPoses(); const Landmarks & structure = sfm_data.GetLandmarks(); openMVG::cameras::Pinhole_Intrinsic pinhole_camera; if(size_cubic_images > 0) pinhole_camera = spherical::ComputeCubicCameraIntrinsics(size_cubic_images); // generate views and camera poses for each new views int error_status = 0; #pragma omp parallel for shared(error_status) if(error_status < 1) for (int i = 0; i < static_cast<int>(views.size()); ++i) { ++my_progress_bar; auto view_it = views.begin(); std::advance(view_it, i); const View * view = view_it->second.get(); if (!sfm_data.IsPoseAndIntrinsicDefined(view)) continue; Intrinsics::const_iterator iter_intrinsic = sfm_data.GetIntrinsics().find(view->id_intrinsic); const IntrinsicBase * cam = iter_intrinsic->second.get(); if (cam && cam->getType() == CAMERA_SPHERICAL) { // We have a valid view with a corresponding camera & pose const std::string view_path = stlplus::create_filespec(sfm_data.s_root_path, view->s_Img_path); image::Image<image::RGBColor> spherical_image; if (!ReadImage(view_path.c_str(), &spherical_image)) { std::cerr << "Cannot read the input panoramic image: " << view_path << std::endl; #pragma omp atomic ++error_status; continue; } if(size_cubic_images <= 0) { const int auto_cubic_size = spherical_image.Height()/2; pinhole_camera = spherical::ComputeCubicCameraIntrinsics(auto_cubic_size); } const std::array<Mat3,6> rot_matrix = spherical::GetCubicRotations(); // when cubical image computation is needed std::vector<image::Image<image::RGBColor>> cube_images; if (force_recompute_images) { std::vector<Mat3> rot_matrix_transposed(rot_matrix.cbegin(), rot_matrix.cend()); std::transform( rot_matrix_transposed.begin(), rot_matrix_transposed.end(), rot_matrix_transposed.begin(), [](const Mat3 & mat) -> Mat3 { return mat.transpose(); }); spherical::SphericalToPinholes( spherical_image, pinhole_camera, cube_images, rot_matrix_transposed, image::Sampler2d<image::SamplerLinear>()); } for (const int cubic_image_id : {0,1,2,3,4,5}) { std::ostringstream os; os << std::setw(8) << std::setfill('0') << cubic_image_id; const std::string dst_cube_image = stlplus::create_filespec( stlplus::folder_append_separator(s_out_dir), stlplus::basename_part(view_path) + "_perspective_" + os.str(), "png"); // when cubical image computation is needed if (force_recompute_images) { if (!WriteImage(dst_cube_image.c_str(), cube_images[cubic_image_id])) { OPENMVG_LOG_ERROR << "Cannot export cubic images to: " << dst_cube_image; #pragma omp atomic ++error_status; continue; } } const View v( stlplus::filename_part(dst_cube_image), view->id_view * 6 + cubic_image_id, // Id view 0, // Id intrinsic view->id_pose * 6 + cubic_image_id, // Id pose pinhole_camera.w(), pinhole_camera.h()); sfm_data_out.views[v.id_view] = std::make_shared<View>(v); // due to 360 cameras, rotation after BA might come with determinant -1 // if so, negate the rotation for future use. Mat3 tmp_rotation = poses.at(view->id_pose).rotation(); if (tmp_rotation.determinant() < 0) { OPENMVG_LOG_INFO << "Negative determinant"; tmp_rotation = tmp_rotation*(-1.0f); } sfm_data_out.poses[v.id_pose] = Pose3(rot_matrix[cubic_image_id] * tmp_rotation, poses.at(view->id_pose).center()); if (sfm_data_out.GetIntrinsics().count(v.id_intrinsic) == 0) sfm_data_out.intrinsics[v.id_intrinsic] = std::make_shared<Pinhole_Intrinsic>(pinhole_camera); } } else { OPENMVG_LOG_INFO << "Loaded scene does not have spherical camera"; #pragma omp atomic ++error_status; continue; } } // end of generate views and camera poses for each new views if (error_status > 0) // early exit return EXIT_FAILURE; // generate structure and associate it with new camera views { system::LoggerProgress my_progress_bar(structure.size(), "Creating cubic sfm_data structure:"); for (const auto & it_structure : structure) { ++my_progress_bar; const Observations & obs = it_structure.second.obs; Landmark out_landmark; out_landmark.X = it_structure.second.X; // iterate across 360 views that can see the point for(const auto & it_obs : obs) { const IndexT pano_view_key = it_obs.first; const IndexT feature_key = it_obs.second.id_feat; // get cubical camera ids and poses and reproject to see if the 3D point is inside the view bool is_reprojection_found = false; for (IndexT local_view_index = pano_view_key * 6; local_view_index < pano_view_key * 6 + 6; ++local_view_index) { const IndexT intrinsic_id = sfm_data_out.views[local_view_index]->id_intrinsic; const IndexT extrinsic_id = sfm_data_out.views[local_view_index]->id_pose; const Pose3 pose = sfm_data_out.poses[extrinsic_id]; const auto cam = sfm_data_out.intrinsics[intrinsic_id]; const int image_height = cam->h(); const int image_width = cam->w(); const Vec2 projection = cam->project(pose(it_structure.second.X)); if (projection.x() < 0 || projection.x() >= image_width || projection.y() < 0 || projection.y() >= image_height) continue; const Vec3 point_to_cam_dir = (it_structure.second.X - pose.center()).normalized(); const Vec3 cam_looking_dir = (pose.rotation().transpose() * Vec3(0, 0, 1)).normalized(); const double angle = R2D(acos(point_to_cam_dir.dot(cam_looking_dir))); if (angle < 0 || angle > 90) continue; out_landmark.obs[local_view_index] = Observation(projection, feature_key); is_reprojection_found = true; break; // if one of the 6 views observe the 3D point, no other views from the 6 views should observe it } // end of looping 6 view of 1 pano image assert(is_reprojection_found); // make sure the observation is found } // end of observations from all panos sfm_data_out.structure.insert({it_structure.first, out_landmark}); } } } // end of converting spherical view to cubical if (!Save(sfm_data_out, stlplus::create_filespec(stlplus::folder_append_separator(s_out_dir), "sfm_data_perspective.bin"), ESfM_Data(ALL))) { OPENMVG_LOG_ERROR << std::endl << "Cannot save the output sfm_data file"; return EXIT_FAILURE; } OPENMVG_LOG_INFO << " #views: " << sfm_data_out.views.size() << "\n" << " #poses: " << sfm_data_out.poses.size() << "\n" << " #intrinsics: " << sfm_data_out.intrinsics.size() << "\n" << " #tracks: " << sfm_data_out.structure.size(); // Exit program return EXIT_SUCCESS; }
10,656
C++
.cpp
237
37.185654
119
0.624277
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,839
main.cpp
openMVG_openMVG/src/software/opencv/accv12_demo/main.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. // Implementation corresponding to the ACCV12 demo: // Adaptive model estimation, a real time demonstration. // Pierre Moulon, Pascal Monasse and Renaud Marlet. // In 11th Asian Confence on Computer Vision (ACCV 2012) #include <iostream> #include <string> #include <vector> #include <fstream> #include <sstream> #include <cv.h> #include <highgui.h> #include <cvaux.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/nonfree/features2d.hpp> #include <opencv2/legacy/legacy.hpp> #include "openMVG/numeric/numeric.h" #include "openMVG/multiview/solver_homography_kernel.hpp" #include "openMVG/multiview/conditioning.hpp" using namespace openMVG; #include "openMVG/robust_estimation/robust_estimator_MaxConsensus.hpp" #include "openMVG/robust_estimation/score_evaluator.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp" using namespace openMVG::robust; #include <boost/circular_buffer.hpp> #include <numeric> using namespace cv; // Number of the frames processed per second in the application int fps; // Estimates the fps of the application void fpsCalculation(void) { static int64 currentTime, lastTime = cvGetTickCount(); static int fpsCounter = 0; currentTime = cvGetTickCount(); ++fpsCounter; // If 1 second has passed since the last FPS estimation, update the fps if (currentTime - lastTime > 1e6 * cvGetTickFrequency()) { fps = fpsCounter; lastTime = currentTime; fpsCounter = 0; } } int fontFace = CV_FONT_HERSHEY_PLAIN; double fontScale = 1; int thickness = 1; int main(int, char**) { cout << "Press:" << endl << " 'q' to quit." << endl; cv::VideoCapture cap(1); // open the Left camera int w = 640, h = 480; cap.set(CV_CAP_PROP_FRAME_WIDTH, w); cap.set(CV_CAP_PROP_FRAME_HEIGHT, h); if (!cap.isOpened() ) // check if we succeeded { std::cerr << "ERROR: Could not open cameras." << std::endl; return -1; } std::vector< cv::KeyPoint > kptsStream; kptsStream.reserve(5000); cv::Mat descriptorsStream; bool bDoRansac = true; Ptr<FeatureDetector> detector; detector = new SiftFeatureDetector; Ptr<DescriptorExtractor> extractor; extractor = new FREAK(true, true); std::vector< cv::KeyPoint > kpts; cv::Mat desc; std::string filename = string(THIS_SOURCE_DIR) + string("/ACCVPattern.jpg"); cv::Mat imgA = imread( filename.c_str(), CV_LOAD_IMAGE_GRAYSCALE ); cv::Mat imgAColor = imread(filename, CV_LOAD_IMAGE_COLOR ); //Build template reference : { detector->detect(imgA, kpts); extractor->compute(imgA, kpts, desc); std::cout << "-------------------\n" << "template : " << kpts.size() << " points" << "-------------------\n" << std::endl; } cv::Mat sidebyside; sidebyside.create(std::max(imgA.rows, h)+10, imgA.cols+w+10, CV_8UC3); //copy template drawKeypoints(imgAColor, kpts, imgAColor); imgAColor.copyTo(sidebyside.colRange(0,0+imgAColor.cols).rowRange(0,0+imgAColor.rows)); BFMatcher matcher(NORM_HAMMING, true); std::vector<cv::DMatch> vec_matches; //-------- //-- Statistics boost::circular_buffer<double> cb_ACRANSAC_Threshold(100,0); boost::circular_buffer<int> cb_ACRANSAC_found(100,0); boost::circular_buffer<int> cb_RANSAC_found(100,0); boost::circular_buffer<double> cb_ACRANSAC_inlierPourcent(100,0); boost::circular_buffer<double> cb_RANSAC_inlierPourcent(100,0); cv::namedWindow("WEBCAM STREAM",CV_WINDOW_AUTOSIZE); for (;;) { bool isValid = true; fpsCalculation(); cv::Mat frame, grayFrame; try { cap >> frame; // get a new frame from left camera cv::cvtColor(frame, grayFrame, CV_RGB2GRAY); detector->detect(grayFrame, kptsStream); extractor->compute( grayFrame, kptsStream, descriptorsStream ); //std::cout << "KpFound : \t" << kptsStream.size() << std::endl; } catch ( cv::Exception& e ) { std::cout << "An exception occurred. Ignoring frame. " << e.err << std::endl; isValid = false; } if (isValid) { try { static char text[256]; sprintf(text, "FPS: %d", fps); int baseline = 0; Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline); putText(frame, text, cv::Point(10, 30), fontFace, fontScale, Scalar::all(255), thickness, 8); drawKeypoints(frame, kptsStream, frame); matcher.match(desc, descriptorsStream, vec_matches); //std::cout << "found : " << vec_matches.size() << "matches" << std::endl; frame.copyTo(sidebyside.colRange(imgA.cols,imgA.cols+frame.cols).rowRange(0,frame.rows)); //------- //-- Robust Model estimation : //------- openMVG::Mat xA(2,vec_matches.size()), xB(2, vec_matches.size()); const std::vector<cv::KeyPoint >& keypointsA = kpts; const std::vector<cv::KeyPoint >& keypointsB = kptsStream; for (size_t i = 0; i < vec_matches.size(); ++i) { const DMatch& match = vec_matches[i]; xA.col(i) = Vec2(keypointsA[match.queryIdx].pt.x, keypointsA[match.queryIdx].pt.y); xB.col(i) = Vec2(keypointsB[match.trainIdx].pt.x, keypointsB[match.trainIdx].pt.y); } //-- Homography robust estimation std::vector<uint32_t> vec_inliers, vec_inliersRansac; Mat3 H; Mat3 Hransac; double thresholdransac = 2.0; double thresholdH = 4.0; double NFAH; { typedef ACKernelAdaptor< openMVG::homography::kernel::FourPointSolver, openMVG::homography::kernel::AsymmetricError, UnnormalizerI, Mat3> KernelType; KernelType kernel( xA, imgA.cols, imgA.rows, xB, frame.cols, frame.rows, false); // configure as point to point error model. double error = std::numeric_limits<double>::infinity(); const std::pair<double,double> ACRansacOut = ACRANSAC(kernel, vec_inliers, 1024, &H, error, false); thresholdH = ACRansacOut.first; NFAH = ACRansacOut.second; } { typedef homography::kernel::Kernel KernelType; KernelType kernel(xA, xB); if (bDoRansac) Hransac = MaxConsensus(kernel, ScorerEvaluator<KernelType>(Square(thresholdransac)), &vec_inliersRansac, 1024); if (vec_inliersRansac.size()<12) thresholdransac = 900; } std::vector<char> vec_matchesMask(vec_matches.size(), 0); for (size_t i = 0; i < vec_inliers.size(); ++i) vec_matchesMask[ vec_inliers[i] ] = 1; static const int Lthickness = 3; Scalar ACColor(255,255,255); Scalar RColor(255,0,255); bool bDrawRansac = thresholdransac < 40; bool bDrawACRansac = thresholdH < 15 && vec_inliers.size() > 12; if (bDrawACRansac) drawMatches(imgA, kpts, frame, kptsStream, vec_matches, sidebyside, Scalar(0,255,0), Scalar(0,255,255), vec_matchesMask); if (bDrawRansac) { cb_RANSAC_found.push_back(1); cb_RANSAC_inlierPourcent.push_back(vec_inliersRansac.size()/float(vec_matches.size())); //Draw warp Vec2 x0(0,0), x1(imgA.cols, 0), x2(imgA.cols, imgA.rows), x3(0, imgA.rows); Vec3 x00 = Hransac * x0.homogeneous(); Vec3 x11 = Hransac * x1.homogeneous(); Vec3 x22 = Hransac * x2.homogeneous(); Vec3 x33 = Hransac * x3.homogeneous(); x0 = x00.hnormalized(); x1 = x11.hnormalized(); x2 = x22.hnormalized(); x3 = x33.hnormalized(); line(sidebyside, Point(x0(0)+imgA.cols, x0(1)), Point(x1(0)+imgA.cols, x1(1)), RColor, Lthickness); line(sidebyside, Point(x1(0)+imgA.cols, x1(1)), Point(x2(0)+imgA.cols, x2(1)), RColor, Lthickness); line(sidebyside, Point(x2(0)+imgA.cols, x2(1)), Point(x3(0)+imgA.cols, x3(1)), RColor, Lthickness); line(sidebyside, Point(x3(0)+imgA.cols, x3(1)), Point(x0(0)+imgA.cols, x0(1)), RColor, Lthickness); } else{ cb_RANSAC_found.push_back(0); cb_RANSAC_inlierPourcent.push_back(0); } if (bDrawACRansac) { cb_ACRANSAC_Threshold.push_back(thresholdH); cb_ACRANSAC_found.push_back(1); cb_ACRANSAC_inlierPourcent.push_back(vec_inliers.size()/float(vec_matches.size())); //Draw warp Vec2 x0(0,0), x1(imgA.cols, 0), x2(imgA.cols, imgA.rows), x3(0, imgA.rows); Vec3 x00 = H * Vec3(x0(0), x0(1), 1); Vec3 x11 = H * Vec3(x1(0), x1(1), 1); Vec3 x22 = H * Vec3(x2(0), x2(1), 1); Vec3 x33 = H * Vec3(x3(0), x3(1), 1); x0 = x00.head<2>() / x00(2); x1 = x11.head<2>() / x11(2); x2 = x22.head<2>() / x22(2); x3 = x33.head<2>() / x33(2); line(sidebyside, Point(x0(0)+imgA.cols, x0(1)), Point(x1(0)+imgA.cols, x1(1)), ACColor, Lthickness); line(sidebyside, Point(x1(0)+imgA.cols, x1(1)), Point(x2(0)+imgA.cols, x2(1)), ACColor, Lthickness); line(sidebyside, Point(x2(0)+imgA.cols, x2(1)), Point(x3(0)+imgA.cols, x3(1)), ACColor, Lthickness); line(sidebyside, Point(x3(0)+imgA.cols, x3(1)), Point(x0(0)+imgA.cols, x0(1)), ACColor, Lthickness); std::stringstream stext; stext << " inlier/outlier ratio: " << vec_inliers.size()/float(vec_matches.size()); baseline = 0; textSize = getTextSize(stext.str().c_str(), fontFace, fontScale, thickness, &baseline); putText(sidebyside, stext.str().c_str(), cv::Point(imgA.cols+10, 60), fontFace, fontScale, Scalar::all(255), thickness, 8); } else { thresholdH = 0; vec_inliers.resize(0); cb_ACRANSAC_Threshold.push_back(0.0); cb_ACRANSAC_found.push_back(0); cb_ACRANSAC_inlierPourcent.push_back(0); } cv::imshow("WEBCAM STREAM", sidebyside); //-- Display stats: cv::Mat plotImg = cv::Mat::zeros( 100 , cb_ACRANSAC_Threshold.size(), CV_8UC3); cv::Point * arrayA = new cv::Point[100]; for (int i=0; i < cb_ACRANSAC_Threshold.size(); ++i){ arrayA[i] = Point(i, 100-cb_ACRANSAC_Threshold[i]*5.0); } int nCurvePts[1]={cb_ACRANSAC_Threshold.size()}; cv::polylines(plotImg, (const cv::Point**)&arrayA, nCurvePts, 1, false, ACColor, 1); std::stringstream stext; stext << "T = :" << thresholdH; baseline = 0; textSize = getTextSize(stext.str().c_str(), fontFace, fontScale, thickness, &baseline); putText(plotImg, stext.str().c_str(), cv::Point(10, 100-80), fontFace, fontScale, Scalar::all(255), thickness, 8); cv::imshow("AC-RANSAC Threshold", plotImg); //Display found/not found plotImg = cv::Mat::zeros( 100 , cb_ACRANSAC_Threshold.size(), CV_8UC3); for (int i=0; i < cb_ACRANSAC_Threshold.size(); ++i){ arrayA[i] = Point(i, cb_ACRANSAC_found[i]*8.0); } cv::polylines(plotImg, (const cv::Point**)&arrayA, nCurvePts, 1, false, ACColor, 2); for (int i=0; i < cb_RANSAC_found.size(); ++i){ arrayA[i] = Point(i, cb_RANSAC_found[i]*8.0 + 50); } cv::polylines(plotImg, (const cv::Point**)&arrayA, nCurvePts, 1, false, RColor, 2); stext.str(""); stext << "#found :" << std::accumulate(cb_ACRANSAC_found.begin(), cb_ACRANSAC_found.end(), 0); baseline = 0; textSize = getTextSize(stext.str().c_str(), fontFace, fontScale, thickness, &baseline); putText(plotImg, stext.str().c_str(), cv::Point(1, 30), fontFace, fontScale, Scalar::all(255), thickness, 8); stext.str(""); stext << "#found :" << std::accumulate(cb_RANSAC_found.begin(), cb_RANSAC_found.end(), 0); baseline = 0; textSize = getTextSize(stext.str().c_str(), fontFace, fontScale, thickness, &baseline); putText(plotImg, stext.str().c_str(), cv::Point(1, 80), fontFace, fontScale, Scalar::all(255), thickness, 8); cv::imshow("Found/NotFound", plotImg); //Display inliers pourcentage plotImg = cv::Mat::zeros( 104 , cb_ACRANSAC_inlierPourcent.size(), CV_8UC3); for (int i=0; i < cb_ACRANSAC_inlierPourcent.size(); ++i){ arrayA[i] = Point(i, 100-cb_ACRANSAC_inlierPourcent[i]*100.0); } cv::polylines(plotImg, (const cv::Point**)&arrayA, nCurvePts, 1, false, ACColor, 1); for (int i=0; i < cb_RANSAC_inlierPourcent.size(); ++i){ arrayA[i] = Point(i, 100-cb_RANSAC_inlierPourcent[i]*100.0); } cv::polylines(plotImg, (const cv::Point**)&arrayA, nCurvePts, 1, false, RColor, 1); stext.str(""); stext << "AC Inlier"; baseline = 0; textSize = getTextSize(stext.str().c_str(), fontFace, fontScale, thickness, &baseline); putText(plotImg, stext.str().c_str(), cv::Point(1, 20), fontFace, fontScale, Scalar::all(255), thickness, 8); stext.str(""); stext << (int)(vec_inliers.size()/float(vec_matches.size())*100) << "%"; baseline = 0; textSize = getTextSize(stext.str().c_str(), fontFace, fontScale, thickness, &baseline); putText(plotImg, stext.str().c_str(), cv::Point(1, 40), fontFace, fontScale, Scalar::all(255), thickness, 8); cv::imshow("InlierPourcent", plotImg); delete [] arrayA; } catch ( cv::Exception& e ) { std::cout << "An exception occurred. Ignoring frame. " << e.err << std::endl; } } bool bQuit = false; const char key = cvWaitKey(30); switch (key) { case 'q': case 'Q': bQuit = true; break; case 'c': case 'C': { fill_n(cb_ACRANSAC_Threshold.begin(),cb_ACRANSAC_Threshold.size(),0); fill_n(cb_ACRANSAC_found.begin(),100,0); fill_n(cb_RANSAC_found.begin(),100,0); fill_n(cb_ACRANSAC_inlierPourcent.begin(),100,0.0); fill_n(cb_RANSAC_inlierPourcent.begin(),100,0.0); } break; case 'r': case 'R': bDoRansac = !bDoRansac; break; } if (bQuit) break; } // the camera object will be automatically released in VideoCapture destructor return 0; }
15,498
C++
.cpp
342
36.225146
125
0.594152
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
true
false
false
26,840
main_ColHarmonize.cpp
openMVG_openMVG/src/software/colorHarmonize/main_ColHarmonize.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2013, 2014 openMVG authors. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "software/colorHarmonize/colorHarmonizeEngineGlobal.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include "openMVG/system/timer.hpp" #include <cstdlib> #include <memory> using namespace openMVG; int main( int argc, char **argv ) { std::cout << "Global Color Harmonization" << std::endl << std::endl; CmdLine cmd; std::string sSfM_Data_Filename; std::string sMatchesDir, sMatchesFile; std::string sOutDir = ""; int selectionMethod = -1; int imgRef = -1; cmd.add( make_option( 'i', sSfM_Data_Filename, "input_file" ) ); cmd.add( make_option( 'm', sMatchesFile, "matchesFile" ) ); cmd.add( make_option( 'o', sOutDir, "outdir" ) ); cmd.add( make_option( 's', selectionMethod, "selectionMethod" ) ); cmd.add( make_option( 'r', imgRef, "referenceImage" ) ); try { if (argc == 1 ) throw std::string( "Invalid command line parameter." ); cmd.process( argc, argv ); } catch ( const std::string& s ) { OPENMVG_LOG_INFO << "Usage: " << argv[ 0 ] << '\n' << "[-i|--input_file] path to a SfM_Data scene\n" << "[-m|--sMatchesFile path] i.e path/matches.(h/f/e).txt\n" << "[-o|--outdir path]\n" << "\n[Optional]\n" << "[-s|--selectionMethod int]\n" << "[-r|--referenceImage int]"; OPENMVG_LOG_ERROR << s; return EXIT_FAILURE; } if ( sSfM_Data_Filename.empty() ) { OPENMVG_LOG_ERROR << "\nIt is an invalid file input"; return EXIT_FAILURE; } if ( !stlplus::folder_exists( sOutDir ) ) stlplus::folder_create( sOutDir ); //--------------------------------------- // Harmonization process //--------------------------------------- openMVG::system::Timer timer; sMatchesDir = stlplus::folder_part(sMatchesFile); std::unique_ptr<ColorHarmonizationEngineGlobal> m_colorHarmonizeEngine( new ColorHarmonizationEngineGlobal(sSfM_Data_Filename, sMatchesDir, sMatchesFile, sOutDir, selectionMethod, imgRef)); if ( m_colorHarmonizeEngine->Process() ) { OPENMVG_LOG_INFO << "ColorHarmonization took (s): " << timer.elapsed(); return EXIT_SUCCESS; } OPENMVG_LOG_ERROR << "Something goes wrong in the process"; return EXIT_FAILURE; }
2,610
C++
.cpp
72
32.416667
76
0.652502
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,842
features_affine_demo.cpp
openMVG_openMVG/src/openMVG_Samples/features_affine_demo/features_affine_demo.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON, Romuald PERROT. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/features/feature.hpp" #include "openMVG/features/mser/mser.hpp" #include "openMVG/features/mser/mser_region.hpp" #include "openMVG/features/tbmr/tbmr.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/image/image_drawing.hpp" #include "openMVG/image/image_resampling.hpp" #include "openMVG/image/sample.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include "third_party/cmdLine/cmdLine.h" #include <unsupported/Eigen/MatrixFunctions> #include <iostream> #include <string> using namespace openMVG; using namespace openMVG::image; using namespace openMVG::features; /** ** Normalize a patch to a specified size, given an ellipse ** Ie: build a patch **/ template <typename Image> void NormalizePatch ( const Image & src_img , const AffinePointFeature & feat , const int patch_size , Image & out_patch ) { // Mapping function Eigen::Matrix<double,2,2> A; A << feat.a(), feat.b(), feat.b(), feat.c(); // Inverse square root A = A.pow( -0.5 ); const float sc = 2.f * 3.f / static_cast<float>(patch_size); A = A * sc; const float half_width = static_cast<float>( patch_size ) / 2.f; // Compute sampling grid std::vector<std::pair<float,float>> sampling_grid; sampling_grid.reserve(patch_size*patch_size); for (int i = 0; i < patch_size; ++i ) { for (int j = 0; j < patch_size; ++j ) { // Apply transformation relative to the center of the patch (assume origin at 0,0 then map to (x,y) ) Vec2 pos; pos << static_cast<float>( j ) - half_width, static_cast<float>( i ) - half_width; // Map (ie: ellipse transform) const Vec2 affineAdapted = A * pos; sampling_grid.emplace_back( affineAdapted(1) + feat.y() , affineAdapted(0) + feat.x() ); } } Sampler2d< SamplerLinear > sampler; // Sample input image to generate patch GenericRessample( src_img , sampling_grid , patch_size , patch_size , sampler , out_patch ); } void Extract_MSER ( const Image<unsigned char> & img, std::vector<features::AffinePointFeature> & feats_dark, std::vector<features::AffinePointFeature> & feats_bright ) { using namespace openMVG::features::MSER; //-- Extract Bight MSER { // Inverted image Image<unsigned char> image4( 255 - img.array() ); std::vector<MSERRegion> regs; MSERExtractor extr4( 2 , 0.0005 , 0.1 , 0.5 , 0.5 , MSERExtractor::MSER_4_CONNECTIVITY ); extr4.Extract( image4 , regs ); for (size_t i = 0; i < regs.size(); ++i ) { double a, b, c; regs[i].FitEllipse( a, b, c ); double x, y; regs[i].FitEllipse( x, y ); feats_bright.emplace_back(x, y, a, b, c); } } //-- Extract Dark MSER { std::vector<MSERRegion> regs; MSERExtractor extr8( 2 , 0.0005 , 0.1 , 0.5 , 0.5 , MSERExtractor::MSER_8_CONNECTIVITY ); extr8.Extract( img , regs ); for (size_t i = 0; i < regs.size(); ++i ) { double a, b, c; regs[i].FitEllipse( a, b, c ); double x, y; regs[i].FitEllipse( x, y ); feats_dark.emplace_back(x, y, a, b, c); } } } void Extract_TBMR ( const Image<unsigned char> & img, std::vector<features::AffinePointFeature> & feats_dark, std::vector<features::AffinePointFeature> & feats_bright ) { tbmr::Extract_tbmr (img, feats_bright, std::less<uint8_t> (), 30); tbmr::Extract_tbmr (img, feats_dark, std::greater<uint8_t> (), 30); } int main(int argc, char **argv) { std::string sAffine_Detector_Method = "TBMR"; CmdLine cmd; cmd.add(make_switch('P', "PATCH")); cmd.add(make_option('d', sAffine_Detector_Method, "detector") ); std::cout << "TBMR Demo:\n" << " Show detected Affine regions as ellipses,\n" << " -[P] in the command line exports square normalized patches for each ellipses.\n" << " -[d|detector] TBMR|MSER Detect TBMR or MSER affine regions." << std::endl; try { cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << s << std::endl; return EXIT_FAILURE; } const std::string sInputDir = stlplus::folder_up(std::string(THIS_SOURCE_DIR)) + "/imageData/SceauxCastle/"; const std::string jpg_filename = sInputDir + "100_7101.jpg"; Image<unsigned char> image; ReadImage(jpg_filename.c_str(), &image); std::vector<features::AffinePointFeature> feats_dark, feats_bright; if (sAffine_Detector_Method == "MSER") { Extract_MSER(image, feats_dark, feats_bright); } else if (sAffine_Detector_Method == "TBMR") { Extract_TBMR(image, feats_dark, feats_bright); } else { std::cerr << "Invalid Affine detector type." << std::endl; return EXIT_FAILURE; } //-- Affine Detector demo: { std::cout << "#detected BRIGHT " << sAffine_Detector_Method << ": " << feats_bright.size() << std::endl; // Display extracted Region ellipses: Image<unsigned char> Icpy (image); for (size_t i = 0; i < feats_bright.size(); ++i) { const AffinePointFeature & fp = feats_bright[i]; DrawEllipse(fp.x(), fp.y(), fp.l1(), fp.l2(), 255, &Icpy, fp.orientation()); if (cmd.used('P')) { //-- Ellipse to square 41x41 patch normalization Image<unsigned char> patch; NormalizePatch( Icpy , fp , 41 , patch ); std::stringstream str; str << "Patch_" << i << ".png"; WriteImage( str.str().c_str() , patch ); } } std::ostringstream os; os << sAffine_Detector_Method << "_BRIGHT_features.jpg"; WriteImage(os.str().c_str(), Icpy); std::cout << "#detected DARK " << sAffine_Detector_Method << ": " << feats_dark.size() << std::endl; // Display extracted Region ellipses: Icpy = image; for (size_t i = 0; i < feats_dark.size(); ++i) { const AffinePointFeature & fp = feats_dark[i]; DrawEllipse(fp.x(), fp.y(), fp.l1(), fp.l2(), 255, &Icpy, fp.orientation()); } os.str(""); os << sAffine_Detector_Method << "_DARK_features.jpg"; WriteImage(os.str().c_str(), Icpy); } return EXIT_SUCCESS; }
6,380
C++
.cpp
188
29.962766
108
0.650057
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,843
siftmatch.cpp
openMVG_openMVG/src/openMVG_Samples/features_siftPutativeMatches/siftmatch.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/features/feature.hpp" #include "openMVG/features/sift/SIFT_Anatomy_Image_Describer.hpp" #include "openMVG/features/svg_features.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/image/image_concat.hpp" #include "openMVG/matching/regions_matcher.hpp" #include "openMVG/matching/svg_matches.hpp" // #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cstdlib> #include <string> #include <iostream> using namespace openMVG; using namespace openMVG::image; using namespace openMVG::matching; int main() { Image<RGBColor> image; std::string jpg_filenameL = stlplus::folder_up(std::string(THIS_SOURCE_DIR)) + "/imageData/StanfordMobileVisualSearch/Ace_0.png"; std::string jpg_filenameR = stlplus::folder_up(std::string(THIS_SOURCE_DIR)) + "/imageData/StanfordMobileVisualSearch/Ace_1.png"; Image<unsigned char> imageL, imageR; ReadImage(jpg_filenameL.c_str(), &imageL); ReadImage(jpg_filenameR.c_str(), &imageR); //-- // Detect regions thanks to an image_describer //-- using namespace openMVG::features; std::unique_ptr<Image_describer> image_describer(new SIFT_Anatomy_Image_describer); std::map<IndexT, std::unique_ptr<features::Regions>> regions_perImage; image_describer->Describe(imageL, regions_perImage[0]); image_describer->Describe(imageR, regions_perImage[1]); const PointFeatures featsL = regions_perImage.at(0)->GetRegionsPositions(), featsR = regions_perImage.at(1)->GetRegionsPositions(); // Show both images side by side { Image<unsigned char> concat; ConcatV(imageL, imageR, concat); std::string out_filename = "00_images.jpg"; WriteImage(out_filename.c_str(), concat); } const SIFT_Regions* regionsL = dynamic_cast<SIFT_Regions*>(regions_perImage.at(0).get()); const SIFT_Regions* regionsR = dynamic_cast<SIFT_Regions*>(regions_perImage.at(1).get()); //- Draw features on the two image (side by side) { Features2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->Features(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->Features(), "01_features.svg" ); } //-- Perform matching -> find Nearest neighbor, filtered with Distance ratio std::vector<IndMatch> vec_PutativeMatches; { // Find corresponding points matching::DistanceRatioMatch( 0.8, matching::BRUTE_FORCE_L2, *regions_perImage.at(0).get(), *regions_perImage.at(1).get(), vec_PutativeMatches); // Draw correspondences after Nearest Neighbor ratio filter const bool bVertical = true; Matches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), vec_PutativeMatches, "02_Matches.svg", bVertical ); } // Display some statistics std::cout << featsL.size() << " Features on image A" << std::endl << featsR.size() << " Features on image B" << std::endl << vec_PutativeMatches.size() << " matches after matching with Distance Ratio filter" << std::endl; return EXIT_SUCCESS; }
3,541
C++
.cpp
92
34.5
102
0.712704
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,845
main_repeatability_dataset.cpp
openMVG_openMVG/src/openMVG_Samples/features_repeatability/main_repeatability_dataset.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/features/feature.hpp" #include "openMVG/features/akaze/image_describer_akaze.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/matching/regions_matcher.hpp" #include "openMVG/multiview/solver_homography_kernel.hpp" #include "openMVG/robust_estimation/guided_matching.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include "third_party/cmdLine/cmdLine.h" #include <string> #include <iostream> using namespace openMVG; using namespace openMVG::image; using namespace openMVG::matching; #include "openMVG/features/sift/SIFT_Anatomy_Image_Describer.hpp" #include "nonFree/sift/SIFT_describer.hpp" // Class to load images and ground truth homography matrices // A reference image // And a series of transformed images with the Homography mapping to the reference class RepeatabilityDataset { public: explicit RepeatabilityDataset ( const std::string& folderPath ): folderPath_(folderPath) { loadImages(); loadGroundTruthHs(); } bool check() const { std::cout << "Dataset: " << folderPath_ << std::endl << "#images: " << vec_image_.size() << "\n" << "#homographies: " << vec_H_.size() << std::endl; return !vec_H_.empty() && !vec_image_.empty() && vec_H_.size() == vec_image_.size(); } const image::Image<RGBColor>& image(size_t i) const { return vec_image_[i]; } const Mat3& H(size_t i) const { return vec_H_[i]; } size_t size() const { return vec_image_.size(); } private: /// Load the images of a directory bool loadImages() { std::cout << "Loading images of the dataset: " << stlplus::folder_part(folderPath_) << std::endl; std::vector<std::string> vec_image_basename = stlplus::folder_wildcard( folderPath_, "*.ppm" ); if (vec_image_basename.empty()) vec_image_basename = stlplus::folder_wildcard( folderPath_, "*.pgm" ); if (vec_image_basename.empty()) return false; sort(vec_image_basename.begin(), vec_image_basename.end()); vec_image_.resize(vec_image_basename.size()); for (size_t i = 0; i < vec_image_basename.size(); ++i) { const std::string path = stlplus::create_filespec(folderPath_, vec_image_basename[i]); image::Image<RGBColor> imageRGB; const bool bReadOk = image::ReadImage(path.c_str(), &imageRGB); if ( bReadOk ) { vec_image_[i] = imageRGB; } else { image::Image<unsigned char> imageGray; if (image::ReadImage(path.c_str(), &imageGray)) { image::ConvertPixelType(imageGray, &imageRGB); vec_image_[i] = imageRGB; } else { std::cerr << "Error: unable to load image:\n" << path << std::endl; return false; } } } return true; } /// Load the Homography related to each read images: /// 0-> Identity, /// 1-> H1to1p, /// 2-> H1to2p, ... bool loadGroundTruthHs() { std::cout << "ground truth homographies of dataset: " << stlplus::folder_part(folderPath_) << std::endl; vec_H_.resize(6); for (int i = 0; i < 6; ++i) { if (i == 0) { vec_H_[i] = Mat3::Identity(); continue; } const std::string path = folderPath_ + "/H1to" + std::to_string(i+1) + "p"; std::ifstream f(path.c_str()); if (!f) { std::cerr << "Error: unable to load ground truth homography:\n" << path << std::endl; return false; } for (int k=0; k<9; ++k) f >> vec_H_[i].data()[k]; vec_H_[i] /= vec_H_[i](2,2); // Display std::cout << "\n\n" << vec_H_[i] << std::endl; } return true; } private: std::string folderPath_; std::vector<image::Image<RGBColor>> vec_image_; std::vector<Mat3> vec_H_; }; /// Export point features based vector to matrices [(x,y)'T, (x,y)'T] template< typename FeaturesT, typename MatT > void PointsToMat( const IndMatches & matches, const FeaturesT & vec_feats0, const FeaturesT & vec_feats1, MatT & m0, MatT & m1) { using ValueT = typename FeaturesT::value_type; // Container type m0.resize(2, matches.size()); m1.resize(2, matches.size()); for (size_t i = 0; i < matches.size(); ++i) { const ValueT & feat0 = vec_feats0[matches[i].i_]; m0.col(i) << feat0.x(), feat0.y(); const ValueT & feat1 = vec_feats1[matches[i].j_]; m1.col(i) << feat1.x(), feat1.y(); } } struct RepeatabilityResults_Matching { std::map<std::string, std::vector<double>> results; bool exportToFile(const std::string & sFile, const std::string & sdatasetName) const { std::ofstream ofs(sFile, std::ofstream::out | std::ofstream::app); if ( ! ofs.good() ) { return false; } ofs << sdatasetName << "\n"; for ( const auto & val : results) { const std::string sParam = val.first; const std::vector<double> & vec = val.second; ofs << sParam << ";"; std::copy(vec.begin(), vec.end(), std::ostream_iterator<double>(ofs, ";")); ofs << "\n"; } ofs.close(); return true; } }; features::EDESCRIBER_PRESET stringToEnum(const std::string & sPreset) { features::EDESCRIBER_PRESET preset; if (sPreset == "NORMAL") preset = features::NORMAL_PRESET; else if (sPreset == "HIGH") preset = features::HIGH_PRESET; else if (sPreset == "ULTRA") preset = features::ULTRA_PRESET; else preset = features::EDESCRIBER_PRESET(-1); return preset; } //-- // Regions repeatability evaluation: // - compare feature/descriptor matching repeatability on some dataset with known homography motions // Must be run one of the dataset contained here: // https://github.com/openMVG/Features_Repeatability // int main(int argc, char **argv) { CmdLine cmd; //-- // Command line parameters std::string sDataset_Path = ""; std::string sImage_Describer_Method = "SIFT"; std::string sFeature_Preset = "NORMAL"; bool bFeature_Repeatability = false; bool bMatching_Repeatability = true; cmd.add( make_option('i', sDataset_Path, "input_dataset") ); cmd.add( make_option('d', sImage_Describer_Method, "describer_method") ); cmd.add( make_option('p', sFeature_Preset, "describer_preset") ); cmd.add( make_option('f', bFeature_Repeatability, "feature_repeatability") ); cmd.add( make_option('m', bMatching_Repeatability, "matching_repeatability") ); //-- //-- // Command line parsing try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_dataset] the path to the datasets \n" << "\n[Optional]\n" << "[-d|--describer_method]\n" << " (method to use to describe an image):\n" << " SIFT (default),\n" << " SIFT_ANATOMY,\n" << " AKAZE_FLOAT: AKAZE with floating point descriptors.\n" << "[-p|--describer_preset]\n" << " (used to control the Image_describer configuration):\n" << " NORMAL (default),\n" << " HIGH,\n" << " ULTRA: !!Can take long time!!\n" << "[-f|--feature_repeatability]\n" << " (used to control the Image_describer configuration):\n" << " 0 (default),\n" << " 1\n" << "[-m|--matching_repeatability]\n" << " 1 (default),\n" << " 0\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } //-- if (bFeature_Repeatability && bMatching_Repeatability) { std::cerr << "Only one repeatability test can be performed at a time." << std::endl; return EXIT_FAILURE; } //-------------------------- // Evaluation parameters //-------------------------- // - Precision radius to accept a point as a valid correspondence const double m_dPrecision_robust = 2.5; // - Nearest neighbor distance ratio to accept a photometric match between some descriptor const double nndr = 0.8; // List all subdirectories and for each one compute the repeatability const std::vector<std::string> vec_dataset_path = stlplus::folder_subdirectories(sDataset_Path); for (auto const& dataset_path : vec_dataset_path) { const std::string sPath = stlplus::create_filespec(sDataset_Path, dataset_path); if (stlplus::is_file(sPath)) continue; RepeatabilityDataset dataset(sPath); if (dataset.check()) { // 1. Compute regions // 2. Test the repeatability (localization/overlap (accuracy)) // 3. Export data using namespace openMVG::features; std::unique_ptr<Image_describer> image_describer; if (sImage_Describer_Method == "SIFT") { image_describer.reset(new SIFT_Image_describer); } else if (sImage_Describer_Method == "SIFT_ANATOMY") { image_describer.reset(new SIFT_Anatomy_Image_describer); } else if (sImage_Describer_Method == "AKAZE_FLOAT") { image_describer = AKAZE_Image_describer::create (AKAZE_Image_describer::Params(AKAZE::Params(), AKAZE_MSURF)); } if (!image_describer) { std::cerr << "Cannot create the designed Image_describer:" << sImage_Describer_Method << "." << std::endl; return EXIT_FAILURE; } else { if (!image_describer->Set_configuration_preset(stringToEnum(sFeature_Preset))) { std::cerr << "Preset configuration failed." << std::endl; return EXIT_FAILURE; } } // For each image computes the regions: image::Image<unsigned char> imageGray; Hash_Map<IndexT, std::unique_ptr<Regions>> map_regions; for (size_t i = 0; i < dataset.size(); ++i) { image::ConvertPixelType(dataset.image(i), &imageGray); image_describer->Describe(imageGray, map_regions[i]); std::cout << "image: " << i << "\t #found features: " << map_regions[i]->RegionCount() << std::endl; } // Repeatability evaluation to the first image // Evaluate the feature positions accuracy (descriptors are ignored) if (bFeature_Repeatability) { RepeatabilityResults_Matching image_results; for (size_t i = 1; i < dataset.size(); ++i) { if (map_regions.count(0) == 0 || map_regions.count(i) == 0) continue; const Regions * regions_0 = map_regions[0].get(); const Regions * regions_I = map_regions[i].get(); const PointFeatures pointsFeatures0 = regions_0->GetRegionsPositions(); const PointFeatures pointsFeaturesI = regions_I->GetRegionsPositions(); Mat x0, xI; PointsToMat(pointsFeatures0, x0); PointsToMat(pointsFeaturesI, xI); IndMatches matches_0I; geometry_aware::GuidedMatching <Mat3, openMVG::homography::kernel::AsymmetricError>( dataset.H(i).transpose(), x0, xI, Square(m_dPrecision_robust), matches_0I); std::cout << "Feature repeatability Results" << "\n" << "*******************************" << "\n" << "# Keypoints 1: \t" << map_regions[0]->RegionCount() << "\n" << "# Keypoints N: \t" << map_regions[i]->RegionCount() << "\n" << "# Inliers: \t" << matches_0I.size() << "\n" << "Inliers Ratio (%): \t" << matches_0I.size() / (float) map_regions[0]->RegionCount() << "\n" << std::endl; const std::vector<double> results = { static_cast<double>( map_regions[0]->RegionCount() ) , static_cast<double>( map_regions[i]->RegionCount() ) , static_cast<double>( matches_0I.size() ) , static_cast<double>( matches_0I.size() / (float) map_regions[0]->RegionCount()) }; image_results.results[std::to_string(i)] = results; } image_results.exportToFile("repeatability_results.xls", stlplus::basename_part(sPath)); } if (bMatching_Repeatability) { // Test the repeatability (matching (descriptor)) RepeatabilityResults_Matching image_results; for (size_t i = 1; i < dataset.size(); ++i) { if (map_regions.count(0) == 0 || map_regions.count(i) == 0) continue; const Regions * regions_0 = map_regions[0].get(); const Regions * regions_I = map_regions[i].get(); const PointFeatures pointsFeatures0 = regions_0->GetRegionsPositions(); const PointFeatures pointsFeaturesI = regions_I->GetRegionsPositions(); matching::IndMatches putativesMatches; matching::DistanceRatioMatch( nndr, matching::BRUTE_FORCE_L2, *regions_0, *regions_I, putativesMatches); Mat x0, xI; PointsToMat(putativesMatches, pointsFeatures0, pointsFeaturesI, x0, xI); IndMatches matches_0I; geometry_aware::GuidedMatching <Mat3, openMVG::homography::kernel::AsymmetricError>( dataset.H(i).transpose(), x0, xI, Square(m_dPrecision_robust), matches_0I); std::cout << "Feature matching repeatability Results" << "\n" << "*******************************" << "\n" << "** " << stlplus::basename_part(sPath) << " **" << "\n" << "*******************************" << "\n" << "# Keypoints 1: \t" << map_regions[0]->RegionCount() << "\n" << "# Keypoints N: \t" << map_regions[i]->RegionCount() << "\n" << "# Matches: \t" << putativesMatches.size() << "\n" << "# Inliers: \t" << matches_0I.size() << "\n" << "Inliers Ratio (%): \t" << matches_0I.size() / (float) putativesMatches.size() << "\n" << std::endl; const std::vector<double> results = { static_cast<double>( map_regions[0]->RegionCount() ) , static_cast<double>( map_regions[i]->RegionCount() ) , static_cast<double>( putativesMatches.size() ) , static_cast<double>( matches_0I.size() ) , static_cast<double>( matches_0I.size() / (double) putativesMatches.size()) }; image_results.results[std::to_string(i)] = results; } image_results.exportToFile("repeatability_results.xls", stlplus::basename_part(sPath)); } } else { std::cerr << "Invalid dataset directory: " << dataset_path << std::endl; return EXIT_FAILURE; } } return EXIT_SUCCESS; }
15,029
C++
.cpp
384
32.799479
125
0.59771
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,847
show_exif_gps_position_demo.cpp
openMVG_openMVG/src/openMVG_Samples/geodesy_show_exif_gps_position/show_exif_gps_position_demo.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2016 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/exif/exif_IO_EasyExif.hpp" #include "openMVG/geodesy/geodesy.hpp" #include "software/SfM/SfMPlyHelper.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include "third_party/cmdLine/cmdLine.h" #include <iostream> #include <memory> #include <string> using namespace openMVG; using namespace openMVG::exif; using namespace openMVG::geodesy; int main(int argc, char **argv) { std::string sInputDirectory = "", sOutputPLYFile = "GPS_POSITION.ply"; CmdLine cmd; cmd.add(make_option('i', sInputDirectory, "input-directory") ); cmd.add(make_option('o', sOutputPLYFile, "output-file") ); try { if (argc == 1) throw std::string("Invalid parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cout << "Geodesy demo:\n" << " Export as PLY points the parsed image EXIF GPS positions,\n" << " -[i|input-directory] Directory that will be parsed.\n" << "-- OPTIONAL PARAMETERS --\n" << " -[o|output-file] Output PLY file.\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } // Loop: Parse images // | If valid GPS data information are found, convert them to XYZ & add it to an array // Export all XYZ parsed data to a PLY file // Init the EXIF reader std::unique_ptr<Exif_IO> exifReader(new Exif_IO_EasyExif); if (!exifReader) { std::cerr << "Cannot instantiate the EXIF metadata reader." << std::endl; return EXIT_FAILURE; } std::vector<Vec3> vec_gps_xyz_position; size_t valid_exif_count = 0; const std::vector<std::string> vec_image = stlplus::folder_files( sInputDirectory ); for (const std::string & it_string : vec_image) { const std::string sImageFilename = stlplus::create_filespec( sInputDirectory, it_string ); // Try to parse EXIF metada exifReader->open( sImageFilename ); // Check existence of EXIF data if (!exifReader->doesHaveExifInfo()) continue; ++valid_exif_count; // Check existence of GPS coordinates double latitude, longitude, altitude; if ( exifReader->GPSLatitude( &latitude ) && exifReader->GPSLongitude( &longitude ) && exifReader->GPSAltitude( &altitude ) ) { // Add ECEF XYZ position to the GPS position array vec_gps_xyz_position.push_back( lla_to_ecef( latitude, longitude, altitude ) ); } } std::cout << std::endl << "Report:\n" << " #file listed: " << vec_image.size() << "\n" << " #valid exif data: " << valid_exif_count << "\n" << " #valid exif gps data: " << vec_gps_xyz_position.size() << std::endl; if ( vec_gps_xyz_position.empty() ) { std::cerr << "No valid GPS data found for the image list" << std::endl; return EXIT_FAILURE; } if ( plyHelper::exportToPly( vec_gps_xyz_position, sOutputPLYFile ) ) { std::cout << sOutputPLYFile << " -> successfully exported on disk." << std::endl; return EXIT_SUCCESS; } return EXIT_FAILURE; }
3,311
C++
.cpp
90
32.922222
94
0.675836
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,849
robust_essential_spherical.cpp
openMVG_openMVG/src/openMVG_Samples/multiview_robust_essential_spherical/robust_essential_spherical.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2017 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/cameras/Camera_Spherical.hpp" #include "openMVG/features/feature.hpp" #include "openMVG/features/sift/SIFT_Anatomy_Image_Describer.hpp" #include "openMVG/features/svg_features.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/image/image_concat.hpp" #include "openMVG/matching/regions_matcher.hpp" #include "openMVG/matching/svg_matches.hpp" #include "openMVG/multiview/conditioning.hpp" #include "openMVG/multiview/essential.hpp" #include "openMVG/multiview/motion_from_essential.hpp" #include "openMVG/multiview/triangulation.hpp" #include "openMVG/multiview/solver_essential_eight_point.hpp" #include "openMVG/multiview/solver_essential_kernel.hpp" #include "openMVG/multiview/solver_essential_three_point.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp" #include "openMVG/sfm/pipelines/sfm_robust_model_estimation.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_BA_ceres.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <iostream> #include <string> using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::geometry; using namespace openMVG::image; using namespace openMVG::matching; using namespace openMVG::robust; using namespace openMVG::sfm; void getRelativePoseAndInliers ( const Mat & xL_spherical_bearings, const Mat & xR_spherical_bearings, std::vector<uint32_t> & vec_inliers, Mat3 & E, const std::string solver_name = "8points" ); int main(int argc, char **argv) { CmdLine cmd; std::string jpg_filenameL, jpg_filenameR, solver_name = "8points"; cmd.add( make_option('a', jpg_filenameL, "input_a") ); cmd.add( make_option('b', jpg_filenameR, "input_b") ); cmd.add( make_option('s', solver_name, "solver")); std::cout << "Compute the relative pose between two spherical image." << "\nUse an Acontrario robust estimation based on angular errors." << "\n- solver can be either: 8points, 5points or 3points (upright)" <<std::endl; try { cmd.process(argc, argv); if (jpg_filenameL.size() == 0 || jpg_filenameR.size() == 0) { const std::string sInputDir = std::string(THIS_SOURCE_DIR); jpg_filenameL = sInputDir + "/SponzaLion000.jpg"; jpg_filenameR = sInputDir + "/SponzaLion001.jpg"; } } catch (const std::string& s) { std::cout << "Invalid usage of arguments -a IMGA -b IMGB" << std::endl; return EXIT_FAILURE; } Image<unsigned char> imageL, imageR; ReadImage(jpg_filenameL.c_str(), &imageL); ReadImage(jpg_filenameR.c_str(), &imageR); std::cout << jpg_filenameL << "\n" << jpg_filenameR << "\n" << solver_name << std::endl; // Setup 2 camera intrinsics cameras::Intrinsic_Spherical cameraL(imageL.Width(), imageL.Height()), cameraR(imageR.Width(), imageR.Height()); //-- // Detect regions thanks to an image_describer //-- using namespace openMVG::features; std::unique_ptr<Image_describer> image_describer (new SIFT_Anatomy_Image_describer(SIFT_Anatomy_Image_describer::Params(-1))); std::map<IndexT, std::unique_ptr<features::Regions>> regions_perImage; image_describer->Describe(imageL, regions_perImage[0]); image_describer->Describe(imageR, regions_perImage[1]); const SIFT_Regions *regionsL = dynamic_cast<const SIFT_Regions*>(regions_perImage.at(0).get()), *regionsR = dynamic_cast<const SIFT_Regions*>(regions_perImage.at(1).get()); const PointFeatures featsL = regions_perImage.at(0)->GetRegionsPositions(), featsR = regions_perImage.at(1)->GetRegionsPositions(); std::cout << "Left image SIFT count: " << featsL.size() << std::endl << "Right image SIFT count: "<< featsR.size() << std::endl; // Show both images side by side { Image<unsigned char> concat; ConcatH(imageL, imageR, concat); std::string out_filename = "01_concat.jpg"; WriteImage(out_filename.c_str(), concat); } //- Draw features on the two image (side by side) { Features2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), "02_features.svg" ); } std::vector<IndMatch> vec_PutativeMatches; //-- Perform matching -> find Nearest neighbor, filtered with Distance ratio { // Find corresponding points matching::DistanceRatioMatch( 0.8, matching::BRUTE_FORCE_L2, *regions_perImage.at(0).get(), *regions_perImage.at(1).get(), vec_PutativeMatches); IndMatchDecorator<float> matchDeduplicator(vec_PutativeMatches, featsL, featsR); matchDeduplicator.getDeduplicated(vec_PutativeMatches); // Draw correspondences after Nearest Neighbor ratio filter const bool bVertical = true; Matches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), vec_PutativeMatches, "03_Matches.svg", bVertical ); } // Essential geometry filtering of putative matches { //A. get back interest point and send it to the robust estimation framework Mat2X xL(2, vec_PutativeMatches.size()), xR(2, vec_PutativeMatches.size()); for (size_t k = 0; k < vec_PutativeMatches.size(); ++k) { const PointFeature & imaL = featsL[vec_PutativeMatches[k].i_]; const PointFeature & imaR = featsR[vec_PutativeMatches[k].j_]; xL.col(k) = imaL.coords().cast<double>(); xR.col(k) = imaR.coords().cast<double>(); } //-- Convert planar to spherical coordinates const Mat xL_spherical = cameraL(xL), xR_spherical = cameraR(xR); //-- Essential matrix robust estimation from spherical bearing vectors { std::vector<uint32_t> vec_inliers; Mat3 E; getRelativePoseAndInliers (xL_spherical, xR_spherical, vec_inliers, E, solver_name); const bool bVertical = true; InlierMatches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), vec_PutativeMatches, vec_inliers, "04_inliers.svg", bVertical ); if (vec_inliers.size() > 60) // 60 is used to filter solution with few common geometric matches (unstable solution) { // Decompose the essential matrix and keep the best solution (if any) geometry::Pose3 relative_pose; std::vector<uint32_t> inliers_indexes; std::vector<Vec3> inliers_X; if (RelativePoseFromEssential(xL_spherical, xR_spherical, E, vec_inliers, &relative_pose, &inliers_indexes, &inliers_X)) { // Lets make a BA on the scene to check if it relative pose and structure can be refined // Setup a SfM scene with two view corresponding the pictures SfM_Data tiny_scene; tiny_scene.views[0].reset(new View("", 0, 0, 0, imageL.Width(), imageL.Height())); tiny_scene.views[1].reset(new View("", 1, 0, 1, imageR.Width(), imageR.Height())); // Setup shared intrinsics camera data tiny_scene.intrinsics[0].reset(new Intrinsic_Spherical(imageR.Width(), imageR.Height())); // Setup poses camera data const Pose3 pose0 = tiny_scene.poses[tiny_scene.views[0]->id_pose] = Pose3(Mat3::Identity(), Vec3::Zero()); const Pose3 pose1 = tiny_scene.poses[tiny_scene.views[1]->id_pose] = relative_pose; // Add a new landmark (3D point with its image observations) for (int i = 0; i < inliers_indexes.size(); ++i) { Landmark landmark; landmark.X = inliers_X[i]; landmark.obs[tiny_scene.views[0]->id_view] = Observation(xL.col(inliers_indexes[i]), 0); landmark.obs[tiny_scene.views[1]->id_view] = Observation(xR.col(inliers_indexes[i]), 0); tiny_scene.structure.insert({tiny_scene.structure.size(), landmark}); } Save(tiny_scene, "EssentialGeometry_start.ply", ESfM_Data(ALL)); // Perform Bundle Adjustment of the scene Bundle_Adjustment_Ceres bundle_adjustment_obj; if (bundle_adjustment_obj.Adjust(tiny_scene, Optimize_Options( Intrinsic_Parameter_Type::NONE, Extrinsic_Parameter_Type::ADJUST_ALL, Structure_Parameter_Type::ADJUST_ALL))) { std::vector<double> residuals; // Compute reprojection error const Pose3 pose0 = tiny_scene.poses[tiny_scene.views[0]->id_pose]; const Pose3 pose1 = tiny_scene.poses[tiny_scene.views[1]->id_pose]; for (const auto & landmark_it : tiny_scene.GetLandmarks()) { const Landmark & landmark = landmark_it.second; const Observations & obs = landmark.obs; Observations::const_iterator iterObs_xI = obs.find(tiny_scene.views[0]->id_view); Observations::const_iterator iterObs_xJ = obs.find(tiny_scene.views[1]->id_view); const Observation & ob_x0 = iterObs_xI->second; const Observation & ob_x1 = iterObs_xJ->second; const Vec2 residual_I = cameraL.residual(pose0(landmark.X), ob_x0.x); const Vec2 residual_J = cameraR.residual(pose1(landmark.X), ob_x1.x); residuals.emplace_back(residual_I.norm()); residuals.emplace_back(residual_J.norm()); } std::cout << "Residual statistics (pixels):" << std::endl; minMaxMeanMedian<double>(residuals.cbegin(), residuals.cend(), std::cout); Save(tiny_scene, "EssentialGeometry_refined.ply", ESfM_Data(ALL)); } } } } } return EXIT_SUCCESS; } template <typename PoseSolverT> void getRelativePoseAndInliers ( const Mat & xL_spherical_bearings, const Mat & xR_spherical_bearings, std::vector<uint32_t> & vec_inliers, Mat3& E ) { // Define the AContrario angular error adaptor using KernelType = openMVG::robust::ACKernelAdaptor_AngularRadianError< PoseSolverT, openMVG::AngularError, Mat3>; KernelType kernel(xL_spherical_bearings, xR_spherical_bearings); // Robust estimation of the Essential matrix and its precision const double precision = std::numeric_limits<double>::infinity(); const std::pair<double,double> ACRansacOut = ACRANSAC(kernel, vec_inliers, 1024, &E, precision, true); const double & threshold = ACRansacOut.first; std::cout << "\n Angular threshold found: " << R2D(threshold) << " (Degree)"<< std::endl; std::cout << "\n #Putatives/#inliers : " << xL_spherical_bearings.cols() << "/" << vec_inliers.size() << "\n" << std::endl; } void getRelativePoseAndInliers ( const Mat & xL_spherical_bearings, const Mat & xR_spherical_bearings, std::vector<uint32_t> & vec_inliers, Mat3& E, const std::string solver_name ) { if (solver_name == "8points") { // Use the 8 point solver in order to estimate E getRelativePoseAndInliers<openMVG::EightPointRelativePoseSolver> (xL_spherical_bearings, xR_spherical_bearings, vec_inliers, E); } else if (solver_name == "5points") { // Use the 5 point solver in order to estimate E getRelativePoseAndInliers<openMVG::essential::kernel::FivePointSolver> (xL_spherical_bearings, xR_spherical_bearings, vec_inliers, E); } else if (solver_name == "3points") { // Use the 3 point solver in order to estimate E getRelativePoseAndInliers<openMVG::essential::kernel::ThreePointUprightRelativePoseSolver> (xL_spherical_bearings, xR_spherical_bearings, vec_inliers, E); } else { std::cerr << "Solvers name can be: 8points, 5points or 3points" << std::endl; } }
12,647
C++
.cpp
296
36.361486
121
0.670378
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,850
main_pano_spherical_to_cubic.cpp
openMVG_openMVG/src/openMVG_Samples/image_spherical_to_cubic/main_pano_spherical_to_cubic.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2019 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/image/image_io.hpp" #include "openMVG/spherical/cubic_image_sampler.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <string> // Convert a spherical panorama to 6 perspective view (cubic panorama) int main(int argc, char **argv) { CmdLine cmd; std::string s_input_image, s_output_image; // required cmd.add( make_option('i', s_input_image, "input_image") ); cmd.add( make_option('o', s_output_image, "output_image") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "[-i|--input_image] the path to the spherical panorama\n" << "[-o|--output_image] the export directory path \n" << std::endl; } if (s_input_image.empty() || s_output_image.empty()) { std::cerr << "input_image and output_image options must not be empty" << std::endl; return EXIT_FAILURE; } using namespace openMVG; image::Image<image::RGBColor> spherical_image; if (!ReadImage(s_input_image.c_str(), &spherical_image)) { std::cerr << "Cannot read the input panoramic image: " << s_input_image << std::endl; return EXIT_FAILURE; } const double cubic_image_size = spherical_image.Width() / 4; // Size can be customized const openMVG::cameras::Pinhole_Intrinsic pinhole_camera = spherical::ComputeCubicCameraIntrinsics(cubic_image_size); std::vector<image::Image<image::RGBColor>> cube_images(6); spherical::SphericalToCubic ( spherical_image, pinhole_camera, cube_images, image::Sampler2d<image::SamplerNearest>() ); if (WriteImage("cube_0.png", cube_images[0]) && WriteImage("cube_1.png", cube_images[1]) && WriteImage("cube_2.png", cube_images[2]) && WriteImage("cube_3.png", cube_images[3]) && WriteImage("cube_4.png", cube_images[4]) && WriteImage("cube_5.png", cube_images[5])) return EXIT_SUCCESS; return EXIT_FAILURE; }
2,395
C++
.cpp
61
35.57377
89
0.68723
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,852
kvld_filter.cpp
openMVG_openMVG/src/openMVG_Samples/features_kvld_filter/kvld_filter.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2013 openMVG authors. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/features/sift/SIFT_Anatomy_Image_Describer.hpp" #include "openMVG/features/svg_features.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/image/image_concat.hpp" #include "openMVG/matching/kvld/kvld.h" #include "openMVG/matching/kvld/kvld_draw.h" #include "openMVG/matching/regions_matcher.hpp" #include "openMVG/matching/svg_matches.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include "openMVG/vector_graphics/svgDrawer.hpp" #include <cstdlib> #include <iostream> #include <string> using namespace openMVG; using namespace openMVG::image; using namespace openMVG::matching; using namespace svg; int main(int argc, char **argv) { CmdLine cmd; std::string sImg1 = stlplus::folder_up(std::string(THIS_SOURCE_DIR)) + "/imageData/StanfordMobileVisualSearch/Ace_0.png"; std::string sImg2 = stlplus::folder_up(std::string(THIS_SOURCE_DIR)) + "/imageData/StanfordMobileVisualSearch/Ace_1.png"; std::string sOutDir = "./kvldOut"; std::cout << sImg1 << std::endl << sImg2 << std::endl; cmd.add( make_option('i', sImg1, "img1") ); cmd.add( make_option('j', sImg2, "img2") ); cmd.add( make_option('o', sOutDir, "outdir") ); if (argc > 1) { try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << ' ' << "[-i|--img1 file] " << "[-j|--img2 file] " << "[-o|--outdir path] " << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } } std::cout << " You called : " <<std::endl << argv[0] << std::endl << "--img1 " << sImg1 << std::endl << "--img2 " << sImg2 << std::endl << "--outdir " << sOutDir << std::endl; if (sOutDir.empty()) { std::cerr << "\nIt is an invalid output directory" << std::endl; return EXIT_FAILURE; } // ----------------------------- // a. List images // b. Compute features and descriptor // c. Compute putatives descriptor matches // d. Geometric filtering of putatives matches // e. Export some statistics // ----------------------------- // Create output dir if (!stlplus::folder_exists(sOutDir)) stlplus::folder_create( sOutDir ); const std::string jpg_filenameL = sImg1; const std::string jpg_filenameR = sImg2; Image<unsigned char> imageL, imageR; ReadImage(jpg_filenameL.c_str(), &imageL); ReadImage(jpg_filenameR.c_str(), &imageR); //-- // Detect regions thanks to an image_describer //-- using namespace openMVG::features; std::unique_ptr<Image_describer> image_describer (new SIFT_Anatomy_Image_describer(SIFT_Anatomy_Image_describer::Params(-1))); std::map<IndexT, std::unique_ptr<features::Regions>> regions_perImage; image_describer->Describe(imageL, regions_perImage[0]); image_describer->Describe(imageR, regions_perImage[1]); const SIFT_Regions* regionsL = dynamic_cast<SIFT_Regions*>(regions_perImage.at(0).get()); const SIFT_Regions* regionsR = dynamic_cast<SIFT_Regions*>(regions_perImage.at(1).get()); const PointFeatures featsL = regions_perImage.at(0)->GetRegionsPositions(), featsR = regions_perImage.at(1)->GetRegionsPositions(); // Show both images side by side { Image<unsigned char> concat; ConcatH(imageL, imageR, concat); std::string out_filename = "00_images.jpg"; WriteImage(out_filename.c_str(), concat); } //- Draw features on the two image (side by side) { Features2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->Features(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->Features(), "01_features.svg" ); } std::vector<IndMatch> vec_PutativeMatches; //-- Perform matching -> find Nearest neighbor, filtered with Distance ratio { // Find corresponding points matching::DistanceRatioMatch( 0.8, matching::BRUTE_FORCE_L2, *regions_perImage.at(0).get(), *regions_perImage.at(1).get(), vec_PutativeMatches); // Draw correspondences after Nearest Neighbor ratio filter const bool bVertical = true; Matches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), vec_PutativeMatches, "02_Matches.svg", bVertical, std::max(std::max(imageL.Width(), imageL.Height()) / float(600), 2.0f) ); } //K-VLD filter Image<float> imgA (imageL.GetMat().cast<float>()); Image<float> imgB (imageR.GetMat().cast<float>()); std::vector<Pair> matchesFiltered; std::vector<Pair> matchesPair; for (const auto & match_it : vec_PutativeMatches) { matchesPair.emplace_back(match_it.i_, match_it.j_); } std::vector<double> vec_score; //In order to illustrate the gvld(or vld)-consistant neighbors, // the following two parameters has been externalized as inputs of the function KVLD. openMVG::Mat E = openMVG::Mat::Ones(vec_PutativeMatches.size(), vec_PutativeMatches.size())*(-1); // gvld-consistancy matrix, intitialized to -1, >0 consistancy value, -1=unknow, -2=false std::vector<bool> valid(vec_PutativeMatches.size(), true);// indices of match in the initial matches, if true at the end of KVLD, a match is kept. size_t it_num=0; KvldParameters kvldparameters; // initial parameters of KVLD while (it_num < 5 && kvldparameters.inlierRate > KVLD(imgA, imgB, regionsL->Features(), regionsR->Features(), matchesPair, matchesFiltered, vec_score,E,valid,kvldparameters)) { kvldparameters.inlierRate /= 2; //std::cout<<"low inlier rate, re-select matches with new rate="<<kvldparameters.inlierRate<<std::endl; kvldparameters.K = 2; it_num++; } std::vector<IndMatch> vec_FilteredMatches; for (std::vector<Pair>::const_iterator i_matchFilter = matchesFiltered.begin(); i_matchFilter != matchesFiltered.end(); ++i_matchFilter){ vec_FilteredMatches.push_back(IndMatch(i_matchFilter->first, i_matchFilter->second)); } //Print K-VLD consistent matches { svgDrawer svgStream(imageL.Width() + imageR.Width(), std::max(imageL.Height(), imageR.Height())); // ".svg" svgStream << svg::drawImage(jpg_filenameL, imageL.Width(), imageL.Height()); svgStream << svg::drawImage(jpg_filenameR, imageR.Width(), imageR.Height(), imageL.Width()); for (size_t it1=0; it1<matchesPair.size()-1;it1++){ for (size_t it2=it1+1; it2<matchesPair.size();it2++){ if (valid[it1] && valid[it2] && E(it1,it2)>=0){ const PointFeature & l1 = featsL[matchesPair[it1].first]; const PointFeature & r1 = featsR[matchesPair[it1].second]; const PointFeature & l2 = featsL[matchesPair[it2].first]; const PointFeature & r2 = featsR[matchesPair[it2].second]; // Compute the width of the current VLD segment float L = (l1.coords() - l2.coords()).norm(); float width = std::max(1.f, L / (dimension+1.f)); // ".svg" svgStream << svg::drawLine(l1.x(), l1.y(), l2.x(), l2.y(), svgAttributes().stroke("yellow", width)); svgStream << svg::drawLine(r1.x() + imageL.Width(), r1.y(), r2.x() + imageL.Width(), r2.y(), svgAttributes().stroke("yellow", width)); } } } const std::string out_filename = stlplus::create_filespec(sOutDir, "03_KVLD_Matches.svg"); std::ofstream svgFile( out_filename.c_str() ); svgFile << svgStream.closeSvgFile().str(); svgFile.close(); } { //Print keypoints kept by K-VLD svgDrawer svgStream(imageL.Width() + imageR.Width(), std::max(imageL.Height(), imageR.Height())); // ".svg" svgStream << svg::drawImage(jpg_filenameL, imageL.Width(), imageL.Height()); svgStream << svg::drawImage(jpg_filenameR, imageR.Width(), imageR.Height(), imageL.Width()); for (size_t it=0; it<matchesPair.size();it++){ if (valid[it]){ const PointFeature & l = featsL[matchesPair[it].first]; const PointFeature & r = featsR[matchesPair[it].second]; // ".svg" svgStream << svg::drawCircle(l.x(), l.y(), 10, svgAttributes().stroke("yellow", 2.0)); svgStream << svg::drawCircle(r.x() + imageL.Width(), r.y(), 10, svgAttributes().stroke("yellow", 2.0)); } } const std::string out_filename = stlplus::create_filespec(sOutDir, "04_KVLD_Keypoints.svg"); std::ofstream svgFile( out_filename.c_str() ); svgFile << svgStream.closeSvgFile().str(); svgFile.close(); } Image <unsigned char> imageOutL = imageL; Image <unsigned char> imageOutR = imageR; getKVLDMask( &imageOutL, &imageOutR, regionsL->Features(), regionsR->Features(), matchesPair, valid, E); { const std::string out_filename = stlplus::create_filespec(sOutDir, "05_Left-K-VLD-MASK.jpg"); WriteImage(out_filename.c_str(), imageOutL); } { const std::string out_filename = stlplus::create_filespec(sOutDir, "06_Right-K-VLD-MASK.jpg"); WriteImage(out_filename.c_str(), imageOutR); } return EXIT_SUCCESS; }
9,666
C++
.cpp
229
37.034934
148
0.65875
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,853
describe_and_match_gmsfilter.cpp
openMVG_openMVG/src/openMVG_Samples/features_image_matching_gmsfilter/describe_and_match_gmsfilter.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/image/image_io.hpp" #include "openMVG/image/image_concat.hpp" #include "openMVG/features/akaze/image_describer_akaze.hpp" #include "openMVG/features/sift/SIFT_Anatomy_Image_Describer.hpp" #include "openMVG/features/svg_features.hpp" #include "openMVG/matching/regions_matcher.hpp" #include "openMVG/matching/svg_matches.hpp" #include "openMVG/robust_estimation/gms_filter.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <memory> #include <string> using namespace openMVG; using namespace openMVG::image; using namespace openMVG::robust; int main(int argc, char **argv) { // Add options to choose the desired Image_describer std::string sImage_describer_type = "SIFT"; CmdLine cmd; cmd.add( make_option('t', sImage_describer_type, "type") ); cmd.add( make_switch('d', "distance_ratio")); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch(const std::string& s) { std::cerr << "Usage: " << argv[0] << '\n' << "\n[Optional]\n" << "[-t|--type\n" << " (choose an image_describer interface):\n" << " SIFT: SIFT keypoint & descriptor,\n" << " AKAZE: AKAZE keypoint & floating point descriptor]\n" << " AKAZE_MLDB: AKAZE keypoint & binary descriptor]\n" << "[-d|distance_ratio] Use distance ratio filter before GMS, else 1-1 matching is used." << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } const std::string jpg_filenameL = stlplus::folder_up(std::string(THIS_SOURCE_DIR)) + "/imageData/StanfordMobileVisualSearch/Ace_0.png"; const std::string jpg_filenameR = stlplus::folder_up(std::string(THIS_SOURCE_DIR)) + "/imageData/StanfordMobileVisualSearch/Ace_1.png"; Image<unsigned char> imageL, imageR; ReadImage(jpg_filenameL.c_str(), &imageL); ReadImage(jpg_filenameR.c_str(), &imageR); assert(imageL.data() && imageR.data()); // Call Keypoint extractor using namespace openMVG::features; std::unique_ptr<Image_describer> image_describer; if (sImage_describer_type == "SIFT") image_describer.reset(new SIFT_Anatomy_Image_describer(SIFT_Anatomy_Image_describer::Params())); else if (sImage_describer_type == "AKAZE") image_describer = AKAZE_Image_describer::create (AKAZE_Image_describer::Params(AKAZE::Params(), AKAZE_MSURF)); else if (sImage_describer_type == "AKAZE_MLDB") image_describer = AKAZE_Image_describer::create (AKAZE_Image_describer::Params(AKAZE::Params(), AKAZE_MLDB)); if (!image_describer) { std::cerr << "Invalid Image_describer type" << std::endl; return EXIT_FAILURE; } // GMS requires to have a lot of features image_describer->Set_configuration_preset(features::ULTRA_PRESET); //-- // Detect regions thanks to the image_describer //-- std::map<IndexT, std::unique_ptr<features::Regions> > regions_perImage; image_describer->Describe(imageL, regions_perImage[0]); image_describer->Describe(imageR, regions_perImage[1]); //-- // Display used images & Features //-- { //- Show images side by side Image<unsigned char> concat; ConcatH(imageL, imageR, concat); const std::string out_filename = "00_images.jpg"; WriteImage(out_filename.c_str(), concat); } { //- Draw features on the images (side by side) Features2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regions_perImage.at(0)->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regions_perImage.at(1)->GetRegionsPositions(), "01_features.svg" ); } //-- // Compute corresponding points //-- //-- Perform matching -> find Nearest neighbor, filtered with Distance ratio matching::IndMatches vec_PutativeMatches; const bool distance_ratio_matching = cmd.used('d'); if (distance_ratio_matching) { const float kDistanceRatio = 0.8f; matching::DistanceRatioMatch( kDistanceRatio, (sImage_describer_type == "AKAZE_MLDB") ? matching::BRUTE_FORCE_HAMMING : matching::BRUTE_FORCE_L2, *regions_perImage.at(0).get(), *regions_perImage.at(1).get(), vec_PutativeMatches); } else { matching::Match( (sImage_describer_type == "AKAZE_MLDB") ? matching::BRUTE_FORCE_HAMMING : matching::BRUTE_FORCE_L2, *regions_perImage.at(0).get(), *regions_perImage.at(1).get(), vec_PutativeMatches); } // Draw the putative photometric correspondences { const bool bVertical = true; Matches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regions_perImage.at(0)->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regions_perImage.at(1)->GetRegionsPositions(), vec_PutativeMatches, "02_Matches.svg", bVertical ); } // Display some statistics std::cout << vec_PutativeMatches.size() << " #matches Found" << std::endl; // Apply the GMS filter { std::vector<Eigen::Vector2f> vec_points_left; { const auto & regions_pos = regions_perImage.at(0)->GetRegionsPositions(); vec_points_left.reserve(regions_pos.size()); for (const auto & it : regions_pos) vec_points_left.push_back({it.x(), it.y()}); } std::vector<Eigen::Vector2f> vec_points_right; { const auto & regions_pos = regions_perImage.at(1)->GetRegionsPositions(); vec_points_right.reserve(regions_pos.size()); for (const auto & it : regions_pos) vec_points_right.push_back({it.x(), it.y()}); } const int kGmsThreshold = 6; robust::GMSFilter gms( vec_points_left, {imageL.Width(), imageL.Height()}, vec_points_right, {imageR.Width(), imageR.Height()}, vec_PutativeMatches, kGmsThreshold); const bool with_scale_invariance = true; const bool with_rotation_invariance = true; std::vector<bool> inlier_flags; const int nb_inliers = gms.GetInlierMask(inlier_flags, with_scale_invariance, with_rotation_invariance); std::cout << vec_points_left.size() << " #Features on image A" << std::endl << vec_points_right.size() << " #Features on image B" << std::endl << nb_inliers << " #matches kept by the GMS Filter" << std::endl; matching::IndMatches vec_gms_matches; for (int i = 0; i < static_cast<int>(inlier_flags.size()); ++i) { if (inlier_flags[i]) vec_gms_matches.push_back(vec_PutativeMatches[i]); } // Draw the correspondences kept by the GMSFilter { const bool bVertical = true; Matches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regions_perImage.at(0)->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regions_perImage.at(1)->GetRegionsPositions(), vec_gms_matches, "03_GMSMatches.svg", bVertical ); } } return EXIT_SUCCESS; }
7,468
C++
.cpp
198
32.343434
100
0.66317
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,854
ImageView.cpp
openMVG_openMVG/src/openMVG_Samples/describe_and_match_GUI/ImageView.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 Romuald Perrot. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "ImageView.hpp" #include <QWheelEvent> #include <cmath> namespace features_pair_demo { /** * @brief ctr * @param scn the scene to render in this widget * @param parent The parent widget */ ImageView::ImageView( QGraphicsScene *scn, QWidget *parent ) : QGraphicsView( scn, parent ) { setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform ); } /** * @brief handling of the zoom effect * @param event Container used to answer the mouse wheel informations */ void ImageView::wheelEvent( QWheelEvent *event ) { // Store current anchor const ViewportAnchor anchor = transformationAnchor(); setTransformationAnchor( QGraphicsView::AnchorUnderMouse ); const qreal factor = std::pow( 1.01, event->angleDelta().y() ); scale( factor, factor ); // Store back current anchor setTransformationAnchor( anchor ); } } // namespace features_pair_demo
1,222
C++
.cpp
35
32.657143
77
0.745964
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,856
MainWindow.cpp
openMVG_openMVG/src/openMVG_Samples/describe_and_match_GUI/MainWindow.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 Romuald Perrot. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "MainWindow.hpp" #include "nonFree/sift/SIFT_describer.hpp" #include "openMVG/features/feature.hpp" #include "openMVG/features/akaze/image_describer_akaze.hpp" #include "openMVG/features/sift/SIFT_Anatomy_Image_Describer.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/matching/regions_matcher.hpp" #include <QApplication> #include <QDir> #include <QFileDialog> #include <QGridLayout> #include <QGroupBox> #include <QMenuBar> #include <QProgressDialog> #include <QString> #include <memory> #include <random> using namespace openMVG::image; using namespace openMVG::features; using namespace openMVG::matching; using namespace openMVG::matching_image_collection; namespace features_pair_demo { /** * @brief Constructor */ MainWindow::MainWindow() { BuildInterface(); BuildMenus(); MakeConnections(); UpdateActivation(); setWindowTitle( "Features pair demo" ); resize( 1024, 768 ); } /** * @brief Action to be done when user wants to load the first image */ void MainWindow::onOpenImage1( void ) { QDir home = QDir::home(); QString file = QFileDialog::getOpenFileName( this, "Open Image 1", home.path(), tr( "Image Files (*.png *.jpg *.pbm *.pgm *.ppm *.tiff)" ) ); if ( !file.isEmpty() && !file.isNull() ) { QImage img( file ); *m_pixmap1 = QPixmap::fromImage( img ); m_scn->removeItem( m_pixmap1Item ); m_pixmap1Item = m_scn->addPixmap( *m_pixmap1 ); m_pixmap1Item->setFlag( QGraphicsItem::ItemIsMovable, true ); // Move the first image relative to the second one QPointF pos = m_pixmap2Item->pos(); pos.setX( pos.x() - m_pixmap1Item->boundingRect().width() ); m_pixmap1Item->setPos( m_pixmap1Item->mapToScene( pos ) ); m_view->fitInView( m_scn->itemsBoundingRect(), Qt::KeepAspectRatio ); m_image1Path = file.toStdString(); ClearFeaturesandMatch(); ClearFeaturesAndMatchItems(); UpdateActivation(); } } /** * @brief Action to be done when user wants to load the second image */ void MainWindow::onOpenImage2( void ) { QDir home = QDir::home(); QString file = QFileDialog::getOpenFileName( this, "Open Image 2", home.path(), tr( "Image Files (*.png *.jpg *.pbm *.pgm *.ppm *.tiff)" ) ); if ( !file.isEmpty() && !file.isNull() ) { QImage img( file ); *m_pixmap2 = QPixmap::fromImage( img ); m_scn->removeItem( m_pixmap2Item ); m_pixmap2Item = m_scn->addPixmap( *m_pixmap2 ); m_pixmap2Item->setFlag( QGraphicsItem::ItemIsMovable, true ); // Move the second image relative to the first one QPointF pos = m_pixmap1Item->pos(); pos.setX( pos.x() + m_pixmap1Item->boundingRect().width() ); m_pixmap2Item->setPos( m_pixmap2Item->mapToScene( pos ) ); m_view->fitInView( m_scn->itemsBoundingRect(), Qt::KeepAspectRatio ); m_image2Path = file.toStdString(); ClearFeaturesandMatch(); ClearFeaturesAndMatchItems(); UpdateActivation(); } } /** * @brief Action to be done when user wants to compute features and matching bewteen image pairs */ void MainWindow::onComputeMatching( void ) { if ( !( m_image1Path.size() > 0 && m_image2Path.size() > 0 ) ) { // TODO : add a message box to tell that we want two image before processing return; } // 0 clear previously computed values ClearFeaturesAndMatchItems(); ClearFeaturesandMatch(); QProgressDialog progress( "Computation in progress ...", "Abort", 0, 4, this ); progress.setWindowModality( Qt::WindowModal ); progress.setMinimumDuration( 0 ); // 1.0 -> Load images from names Image<unsigned char> image1, image2; ReadImage( m_image1Path.c_str(), &image1 ); if ( progress.wasCanceled() ) return; ReadImage( m_image2Path.c_str(), &image2 ); if ( progress.wasCanceled() ) return; progress.setValue( 1 ); // 1.1 Get the describer EDESCRIBER_PRESET preset = GetFeaturePreset(); std::unique_ptr<Image_describer> image_describer = GetFeatureDescriber( preset ); // 1.2 Compute description of the two images Image<unsigned char> *mask = nullptr; // The mask is null by default std::unique_ptr<Regions> regions1, regions2; image_describer->Describe( image1, regions1, mask ); if ( progress.wasCanceled() ) return; image_describer->Describe( image2, regions2, mask ); if ( progress.wasCanceled() ) return; progress.setValue( 2 ); // 2.1 Get matching params const EMatcherType matcherType = GetMatcherType(); const float fDistRatio = static_cast<float>( m_spinDistThreshold->value() ); m_matches.clear(); // 2.1 Matches features DistanceRatioMatch( fDistRatio, matcherType, *regions1.get(), *regions2.get(), m_matches ); if ( progress.wasCanceled() ) { m_matches.clear(); return; } progress.setValue( 3 ); // 3 draw result m_feats1 = regions1->GetRegionsPositions(); m_feats2 = regions2->GetRegionsPositions(); // Position anchor of the images (in global space and local space) const QPointF gpos1 = m_pixmap1Item->pos(); const QPointF gpos2 = m_pixmap2Item->pos(); const QPointF pos1 = m_pixmap1Item->mapFromScene( gpos1 ); const QPointF pos2 = m_pixmap2Item->mapFromScene( gpos2 ); // Default color for unmatched points QPen penFeat( QColor( 0, 0, 0 ) ); // Generate random color per pair std::map<int, QPen> feat1Pen, feat2Pen, matchesPen; std::random_device rd; std::mt19937 rng( rd() ); std::uniform_int_distribution<int> distrib_h( 0, 359 ), distrib_s( 200, 255 ), distrib_v( 200, 255 ); for ( size_t i = 0; i < m_matches.size(); ++i ) { const int id1 = m_matches[ i ].i_; const int id2 = m_matches[ i ].j_; const QColor col = QColor::fromHsv( distrib_h( rng ), distrib_s( rng ), distrib_v( rng ) ); QPen curPen( col ); curPen.setWidth( 2 ); feat1Pen[ id1 ] = curPen; feat2Pen[ id2 ] = curPen; matchesPen[ i ] = curPen; } for ( size_t i = 0; i < m_feats1.size(); ++i ) { QPen &curPen = feat1Pen.count( i ) ? feat1Pen[ i ] : penFeat; const PointFeature &f = m_feats1[ i ]; QGraphicsEllipseItem *ell = m_scn->addEllipse( f.x() + pos1.x(), f.y() + pos1.y(), 10.0, 10.0, curPen ); ell->setParentItem( m_pixmap1Item ); m_ellipsesFeat1.emplace_back( ell ); } for ( size_t i = 0; i < m_feats2.size(); ++i ) { QPen &curPen = feat2Pen.count( i ) ? feat2Pen[ i ] : penFeat; const PointFeature &f = m_feats2[ i ]; QGraphicsEllipseItem *ell = m_scn->addEllipse( f.x() + pos2.x(), f.y() + pos2.y(), 10.0, 10.0, curPen ); ell->setParentItem( m_pixmap2Item ); m_ellipsesFeat2.emplace_back( ell ); } // Correspondances for ( size_t i = 0; i < m_matches.size(); ++i ) { QPen curPen = matchesPen[ i ]; const PointFeature &L = m_feats1[ m_matches[ i ].i_ ]; const PointFeature &R = m_feats2[ m_matches[ i ].j_ ]; m_lineMatch.emplace_back( m_scn->addLine( L.x() + gpos1.x(), L.y() + gpos1.y(), R.x() + gpos2.x(), R.y() + gpos2.y(), curPen ) ); } progress.setValue( 4 ); UpdateActivation(); } /** * @brief Action to be executed when user move image on the interface */ void MainWindow::onMoveSomething( void ) { QGraphicsItem *item = m_scn->mouseGrabberItem(); if ( item == m_pixmap1Item || item == m_pixmap2Item ) { MoveMatchLines(); } } /** * @brief Action to be executed when user wants to export the final computation to an image */ void MainWindow::onExportImage( void ) { QDir home = QDir::home(); QString file = QFileDialog::getSaveFileName( this, "Save File", home.path(), tr( "Images (*.png *.xpm *.jpg)" ) ); if ( !file.isEmpty() && !file.isNull() ) { QPixmap pixMap = m_view->grab(); pixMap.save( file ); } } /** * @brief Action to be executed when user request closing of image 1 */ void MainWindow::onCloseImage1( void ) { m_feats1.clear(); m_matches.clear(); m_image1Path.clear(); for ( auto item : m_ellipsesFeat1 ) { m_scn->removeItem( item ); } for ( auto item : m_lineMatch ) { m_scn->removeItem( item ); } m_ellipsesFeat1.clear(); m_lineMatch.clear(); m_scn->removeItem( m_pixmap1Item ); UpdateActivation(); } /** * @brief Action to be executed when user request closing of image 2 */ void MainWindow::onCloseImage2( void ) { m_feats2.clear(); m_matches.clear(); m_image2Path.clear(); for ( auto item : m_ellipsesFeat2 ) { m_scn->removeItem( item ); } for ( auto item : m_lineMatch ) { m_scn->removeItem( item ); } m_ellipsesFeat2.clear(); m_lineMatch.clear(); m_scn->removeItem( m_pixmap2Item ); UpdateActivation(); } /** * @brief Action to be executed when user request closing both images */ void MainWindow::onCloseAll( void ) { onCloseImage1(); onCloseImage2(); UpdateActivation(); } /** * @brief Action to be executed when user request to quit the application */ void MainWindow::onQuit( void ) { QApplication::quit(); } /** * @brief Action to be executed when user request clearing the computation */ void MainWindow::onClearComputation( void ) { ClearFeaturesandMatch(); ClearFeaturesAndMatchItems(); UpdateActivation(); } /** * @brief Set elements enabled/disabled based on currently loaded elements */ void MainWindow::UpdateActivation( void ) { // has loaded image 1 so we can close it if ( m_image1Path.size() > 0 ) { m_fileCloseImage1->setEnabled( true ); m_fileCloseAll->setEnabled( true ); } else { m_fileCloseImage1->setEnabled( false ); } // has loaded image 2 so we can close it if ( m_image2Path.size() > 0 ) { m_fileCloseImage2->setEnabled( true ); m_fileCloseAll->setEnabled( true ); } else { m_fileCloseImage2->setEnabled( false ); } // No image opened , close all should be removed if ( !( m_image1Path.size() > 0 || m_image2Path.size() > 0 ) ) { m_fileCloseAll->setEnabled( false ); } // Both loaded, could do computation and exportation if ( m_image1Path.size() > 0 && m_image2Path.size() > 0 ) { m_computeMatching->setEnabled( true ); m_processingClearMatch->setEnabled( true ); m_processingComputeMatch->setEnabled( true ); m_fileExportImage->setEnabled( true ); } else { m_computeMatching->setEnabled( false ); m_processingClearMatch->setEnabled( false ); m_processingComputeMatch->setEnabled( false ); m_fileExportImage->setEnabled( false ); } } /** * @brief Build all interface widgets */ void MainWindow::BuildInterface() { // Features QGridLayout *featureLayout = new QGridLayout; QGroupBox *groupFeatures = new QGroupBox( "Feature" ); m_labelFeatureName = new QLabel( "Feature" ); m_labelFeatureMode = new QLabel( "Mode" ); m_checkUpright = new QCheckBox( "Upright" ); m_checkUpright->setTristate( false ); m_checkUpright->setCheckState( Qt::Unchecked ); m_comboFeatureName = new QComboBox; m_comboFeatureMode = new QComboBox; featureLayout->addWidget( m_labelFeatureName, 0, 0 ); featureLayout->addWidget( m_comboFeatureName, 0, 1 ); featureLayout->addWidget( m_labelFeatureMode, 0, 2 ); featureLayout->addWidget( m_comboFeatureMode, 0, 3 ); featureLayout->addWidget( m_checkUpright, 0, 4 ); groupFeatures->setLayout( featureLayout ); // Matching QGroupBox *groupMatching = new QGroupBox( "Matching" ); QGridLayout *matchingLayout = new QGridLayout; m_matchingType = new QLabel( "Matching" ); m_comboMatchingName = new QComboBox; m_labelDistanceThreshold = new QLabel( "Distance" ); m_spinDistThreshold = new QDoubleSpinBox(); m_spinDistThreshold->setDecimals( 3 ); m_spinDistThreshold->setValue( 0.8 ); matchingLayout->addWidget( m_matchingType, 0, 0 ); matchingLayout->addWidget( m_comboMatchingName, 0, 1 ); matchingLayout->addWidget( m_labelDistanceThreshold, 0, 2 ); matchingLayout->addWidget( m_spinDistThreshold, 0, 3 ); groupMatching->setLayout( matchingLayout ); // Processing QGroupBox *groupProcessing = new QGroupBox( "Processing" ); QGridLayout *processingLayout = new QGridLayout; m_loadImage1 = new QPushButton( "Load Image 1" ); m_loadImage2 = new QPushButton( "Load Image 2" ); m_computeMatching = new QPushButton( "Match" ); processingLayout->addWidget( m_loadImage1, 0, 0 ); processingLayout->addWidget( m_computeMatching, 0, 1 ); processingLayout->addWidget( m_loadImage2, 0, 2 ); groupProcessing->setLayout( processingLayout ); // Result QGroupBox *groupResult = new QGroupBox( "Result" ); QGridLayout *resultLayout = new QGridLayout; m_scn = new QGraphicsScene; m_view = new ImageView( m_scn ); m_view->setDragMode( QGraphicsView::ScrollHandDrag ); m_pixmap1 = new QPixmap; m_pixmap2 = new QPixmap; m_pixmap1Item = m_scn->addPixmap( *m_pixmap1 ); m_pixmap2Item = m_scn->addPixmap( *m_pixmap2 ); resultLayout->addWidget( m_view ); groupResult->setLayout( resultLayout ); m_exportResult = new QPushButton( "Export image" ); // Add everything to the window QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->addWidget( groupFeatures ); mainLayout->addWidget( groupMatching ); mainLayout->addWidget( groupProcessing ); mainLayout->addWidget( groupResult ); mainLayout->addWidget( m_exportResult ); QWidget *dummyWidget = new QWidget; dummyWidget->setLayout( mainLayout ); setCentralWidget( dummyWidget ); PopulateFeatureType(); PopulateMatchingType(); } /** * @brief Build all menus items */ void MainWindow::BuildMenus() { // File m_fileMenu = new QMenu( "File" ); m_fileOpenImage1 = m_fileMenu->addAction( "Open image 1" ); m_fileOpenImage2 = m_fileMenu->addAction( "Open image 2" ); m_fileMenu->addSeparator(); m_fileCloseImage1 = m_fileMenu->addAction( "Close image 1" ); m_fileCloseImage2 = m_fileMenu->addAction( "Close image 2" ); m_fileCloseAll = m_fileMenu->addAction( "Close all" ); m_fileCloseAll->setShortcut( QKeySequence::Close ); m_fileMenu->addSeparator(); m_fileExportImage = m_fileMenu->addAction( "Save result image" ); m_fileExportImage->setShortcut( QKeySequence::Save ); m_fileMenu->addSeparator(); m_fileQuit = m_fileMenu->addAction( "Quit" ); m_fileQuit->setShortcut( QKeySequence::Quit ); // Processing m_processingMenu = new QMenu( "Processing" ); m_processingComputeMatch = m_processingMenu->addAction( "Compute match" ); m_processingClearMatch = m_processingMenu->addAction( "Clear computation" ); QMenuBar *menuBar = this->menuBar(); menuBar->addMenu( m_fileMenu ); menuBar->addMenu( m_processingMenu ); } /** * @brief Make connections between interface elements */ void MainWindow::MakeConnections() { // Buttons connect( m_loadImage1, SIGNAL( clicked() ), this, SLOT( onOpenImage1() ) ); connect( m_loadImage2, SIGNAL( clicked() ), this, SLOT( onOpenImage2() ) ); connect( m_computeMatching, SIGNAL( clicked() ), this, SLOT( onComputeMatching() ) ); connect( m_exportResult, SIGNAL( clicked() ), this, SLOT( onExportImage() ) ); // Moving an image connect( m_scn, SIGNAL( changed( const QList<QRectF> & ) ), this, SLOT( onMoveSomething() ) ); // menus connect( m_fileQuit, SIGNAL( triggered() ), this, SLOT( onQuit() ) ); connect( m_fileOpenImage1, SIGNAL( triggered() ), this, SLOT( onOpenImage1() ) ); connect( m_fileOpenImage2, SIGNAL( triggered() ), this, SLOT( onOpenImage2() ) ); connect( m_fileCloseImage1, SIGNAL( triggered() ), this, SLOT( onCloseImage1() ) ); connect( m_fileCloseImage2, SIGNAL( triggered() ), this, SLOT( onCloseImage2() ) ); connect( m_fileCloseAll, SIGNAL( triggered() ), this, SLOT( onCloseAll() ) ); connect( m_fileExportImage, SIGNAL( triggered() ), this, SLOT( onExportImage() ) ); connect( m_processingComputeMatch, SIGNAL( triggered() ), this, SLOT( onComputeMatching() ) ); connect( m_processingClearMatch, SIGNAL( triggered() ), this, SLOT( onClearComputation() ) ); } /** * @brief Get list of all feature type (and mode) */ void MainWindow::PopulateFeatureType() { m_comboFeatureName->addItem( "SIFT" ); m_comboFeatureName->addItem( "SIFT_ANATOMY" ); m_comboFeatureName->addItem( "AKAZE_FLOAT" ); m_comboFeatureName->addItem( "AKAZE_MLDB" ); m_comboFeatureMode->addItem( "NORMAL" ); m_comboFeatureMode->addItem( "HIGH" ); m_comboFeatureMode->addItem( "ULTRA" ); } /** * @brief Get list of all matching type */ void MainWindow::PopulateMatchingType() { m_comboMatchingName->addItem( "BRUTEFORCEL2" ); m_comboMatchingName->addItem( "ANNL2" ); m_comboMatchingName->addItem( "CASCADEHASHINGL2" ); m_comboMatchingName->insertSeparator( 4 ); m_comboMatchingName->addItem( "BRUTEFORCEHAMMING" ); m_comboMatchingName->setCurrentIndex( 1 ); } /** * @brief remove previous computation (internal data) */ void MainWindow::ClearFeaturesandMatch() { m_feats1.clear(); m_feats2.clear(); m_matches.clear(); } /** * @brief remove previous computation on the view (only view data, not internal ones) */ void MainWindow::ClearFeaturesAndMatchItems() { for (auto item : m_ellipsesFeat1 ) { m_scn->removeItem( item ); } for (auto item : m_ellipsesFeat2 ) { m_scn->removeItem( item ); } for (auto item : m_lineMatch ) { m_scn->removeItem( item ); } m_ellipsesFeat1.clear(); m_ellipsesFeat2.clear(); m_lineMatch.clear(); } /** * @brief Redraw match lines at correct position (ie:after image move) */ void MainWindow::MoveMatchLines() { // Position anchor of the images (in global space and local space) QPointF gpos1 = m_pixmap1Item->pos(); QPointF gpos2 = m_pixmap2Item->pos(); for ( size_t i = 0; i < m_matches.size(); ++i ) { const PointFeature &L = m_feats1[ m_matches[ i ].i_ ]; const PointFeature &R = m_feats2[ m_matches[ i ].j_ ]; QGraphicsLineItem *cur_line = m_lineMatch[ i ]; cur_line->setLine( L.x() + gpos1.x(), L.y() + gpos1.y(), R.x() + gpos2.x(), R.y() + gpos2.y() ); } } /** * @brief Get feature preset from interface * @return descriptor preset given the interface choice */ EDESCRIBER_PRESET MainWindow::GetFeaturePreset() { // get selected item const std::string sPreset = m_comboFeatureMode->currentText().toStdString(); EDESCRIBER_PRESET preset; if ( sPreset == "NORMAL" ) { preset = NORMAL_PRESET; } else if ( sPreset == "HIGH" ) { preset = HIGH_PRESET; } else if ( sPreset == "ULTRA" ) { preset = ULTRA_PRESET; } else { std::cerr << "Unknown preset value" << std::endl; } return preset; } /** * @brief Get describer instance based on interface choice * @param preset Current preset * @return An image describer */ std::unique_ptr<Image_describer> MainWindow::GetFeatureDescriber( const EDESCRIBER_PRESET preset ) { const std::string sImage_Describer_Method = m_comboFeatureName->currentText().toStdString(); const bool bUpRight = m_checkUpright->checkState() == Qt::Checked; std::unique_ptr<Image_describer> image_describer; if ( sImage_Describer_Method == "SIFT" ) { image_describer.reset( new SIFT_Image_describer( SIFT_Image_describer::Params(), !bUpRight ) ); } else if ( sImage_Describer_Method == "SIFT_ANATOMY" ) { image_describer.reset( new SIFT_Anatomy_Image_describer( SIFT_Anatomy_Image_describer::Params() ) ); } else if ( sImage_Describer_Method == "AKAZE_FLOAT" ) { image_describer = AKAZE_Image_describer::create( AKAZE_Image_describer::Params( AKAZE::Params(), AKAZE_MSURF ), !bUpRight ); } else if ( sImage_Describer_Method == "AKAZE_MLDB" ) { image_describer = AKAZE_Image_describer::create( AKAZE_Image_describer::Params( AKAZE::Params(), AKAZE_MLDB ), !bUpRight ); } else { std::cerr << "Unknown feature value" << std::endl; } image_describer->Set_configuration_preset( preset ); return image_describer; } /** * @brief Get Matcher type * @return current matcher type based on interface choices */ EMatcherType MainWindow::GetMatcherType( void ) { const std::string sNearestMatchingMethod = m_comboMatchingName->currentText().toStdString(); if ( sNearestMatchingMethod == "BRUTEFORCEL2" ) { return BRUTE_FORCE_L2; } else if ( sNearestMatchingMethod == "BRUTEFORCEHAMMING" ) { return BRUTE_FORCE_HAMMING; } else if ( sNearestMatchingMethod == "ANNL2" ) { return ANN_L2; } else if ( sNearestMatchingMethod == "CASCADEHASHINGL2" ) { return CASCADE_HASHING_L2; } return BRUTE_FORCE_L2; } } // namespace features_pair_demo
21,071
C++
.cpp
622
30.551447
143
0.685658
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,857
visualize_sfm_data.cpp
openMVG_openMVG/src/openMVG_Samples/visualize_sfm_data/visualize_sfm_data.cpp
#include <rerun.hpp> #include "openMVG/image/image_container.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/sfm/sfm.hpp" #include "openMVG/sfm/sfm_data.hpp" #include "openMVG/sfm/sfm_data_io.hpp" #include "openMVG/sfm/sfm_data_utils.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" using namespace std::string_literals; int main(int argc, char* argv[]) { CmdLine cmd; std::string input_sfm_data_path{}; cmd.add(make_option('s', input_sfm_data_path, "sfm_data")); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& ex) { std::cerr << "Usage: " << argv[0] << '\n' << "[-s|--sfm_data] the path for the sfm_data in any " << "format openMVG::sfm::Save supports like .json or .bin\n"; return EXIT_FAILURE; } // load sfm_data from a file. openMVG::sfm::SfM_Data sfm_data; std::string camera_entity{"world/Camera/"}; std::string points3D_entity{"world/Points3D"}; if (stlplus::is_file(input_sfm_data_path)) { openMVG::sfm::Load(sfm_data, input_sfm_data_path, openMVG::sfm::ESfM_Data::ALL); } else { std::cerr << "The entered path is not valid.\n"; return EXIT_FAILURE; } // rerun_sdk const auto rec = rerun::RecordingStream("openMVG_sfm_data_visualization"); rec.spawn().exit_on_failure(); const auto& views_poses = sfm_data.GetPoses(); for (const auto& [view_id, view] : sfm_data.views) { /* be sure that the view->s_Img_path is the full path of the image when sfm_data got exported*/ auto view_file_name = stlplus::filename_part(view->s_Img_path); const auto id_intrinsic = view->id_intrinsic; const auto id_pose = view->id_pose; if (auto it = views_poses.find(id_pose); it != views_poses.end()) { const auto& view_pose = views_poses.at(id_pose); Eigen::Vector3d view_translation = view_pose.translation(); rerun::datatypes::Mat3x3 rr_rotation{ {static_cast<float>(view_pose.rotation()(0, 0)), static_cast<float>(view_pose.rotation()(1, 0)), static_cast<float>(view_pose.rotation()(2, 0)), static_cast<float>(view_pose.rotation()(0, 1)), static_cast<float>(view_pose.rotation()(1, 1)), static_cast<float>(view_pose.rotation()(2, 1)), static_cast<float>(view_pose.rotation()(0, 2)), static_cast<float>(view_pose.rotation()(1, 2)), static_cast<float>(view_pose.rotation()(2, 2))}}; rerun::datatypes::Vec3D rr_translation{ static_cast<float>(view_translation(0)), static_cast<float>(view_translation(1)), static_cast<float>(view_translation(2))}; rec.log( camera_entity + view_file_name, rerun::archetypes::Transform3D(rr_translation, rr_rotation, true)); const rerun::datatypes::Vec2D resolution{ static_cast<float>(view->ui_width), static_cast<float>(view->ui_height)}; rec.log(camera_entity + view_file_name, rerun::archetypes::Pinhole::from_focal_length_and_resolution( sfm_data.GetIntrinsics().at(id_intrinsic)->getParams()[0], resolution)); openMVG::image::Image<openMVG::image::RGBColor> img; const auto image_name = stlplus::create_filespec(sfm_data.s_root_path, view_file_name); auto is_img_loaded = openMVG::image::ReadImage(image_name.c_str(), &img); if (is_img_loaded) { rec.log(camera_entity + view_file_name, rerun::Image( img.GetMat().data()->data(), { static_cast<uint32_t>(img.cols()), static_cast<uint32_t>(img.rows()) }, rerun::datatypes::ColorModel::RGB)); } } } const auto& landmarks = sfm_data.GetLandmarks(); std::vector<rerun::components::Position3D> points3d; std::vector<rerun::components::KeypointId> track_ids; std::unordered_map<uint32_t, std::vector<rerun::components::Position2D>> points2d_per_img; for (const auto& landmark : landmarks) { points3d.emplace_back(landmark.second.X(0), landmark.second.X(1), landmark.second.X(2)); track_ids.push_back(landmark.first); for (const auto& obs : landmark.second.obs) { points2d_per_img[obs.first].push_back( {static_cast<float>(obs.second.x(0)), static_cast<float>(obs.second.x(1))}); } } rec.log(points3D_entity, rerun::archetypes::Points3D(points3d).with_keypoint_ids(track_ids)); for (const auto& view : sfm_data.views) { auto it = points2d_per_img.find(view.first); if (it != points2d_per_img.end()) { rec.log(camera_entity + stlplus::filename_part(view.second->s_Img_path), rerun::archetypes::Points2D(points2d_per_img.at(view.first))); } } return 0; }
4,946
C++
.cpp
110
37.909091
93
0.638174
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,861
robust_fundamental.cpp
openMVG_openMVG/src/openMVG_Samples/multiview_robust_fundamental/robust_fundamental.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2012, 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/features/svg_features.hpp" #include "openMVG/features/sift/SIFT_Anatomy_Image_Describer.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/image/image_concat.hpp" #include "openMVG/matching/regions_matcher.hpp" #include "openMVG/matching/svg_matches.hpp" #include "openMVG/multiview/solver_fundamental_kernel.hpp" #include "openMVG/numeric/eigen_alias_definition.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <iostream> #include <string> #include <utility> using namespace openMVG; using namespace openMVG::image; using namespace openMVG::matching; using namespace openMVG::robust; int main() { const std::string sInputDir = stlplus::folder_up(std::string(THIS_SOURCE_DIR)) + "/imageData/SceauxCastle/"; Image<RGBColor> image; const std::string jpg_filenameL = sInputDir + "100_7101.jpg"; const std::string jpg_filenameR = sInputDir + "100_7102.jpg"; Image<unsigned char> imageL, imageR; ReadImage(jpg_filenameL.c_str(), &imageL); ReadImage(jpg_filenameR.c_str(), &imageR); //-- // Detect regions thanks to an image_describer //-- using namespace openMVG::features; std::unique_ptr<Image_describer> image_describer(new SIFT_Anatomy_Image_describer); std::map<IndexT, std::unique_ptr<features::Regions>> regions_perImage; image_describer->Describe(imageL, regions_perImage[0]); image_describer->Describe(imageR, regions_perImage[1]); const SIFT_Regions* regionsL = dynamic_cast<SIFT_Regions*>(regions_perImage.at(0).get()); const SIFT_Regions* regionsR = dynamic_cast<SIFT_Regions*>(regions_perImage.at(1).get()); const PointFeatures featsL = regions_perImage.at(0)->GetRegionsPositions(), featsR = regions_perImage.at(1)->GetRegionsPositions(); // Show both images side by side { Image<unsigned char> concat; ConcatH(imageL, imageR, concat); std::string out_filename = "01_concat.jpg"; WriteImage(out_filename.c_str(), concat); } //- Draw features on the two image (side by side) { Features2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->Features(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->Features(), "02_features.svg" ); } std::vector<IndMatch> vec_PutativeMatches; //-- Perform matching -> find Nearest neighbor, filtered with Distance ratio { // Find corresponding points matching::DistanceRatioMatch( 0.8, matching::BRUTE_FORCE_L2, *regions_perImage.at(0).get(), *regions_perImage.at(1).get(), vec_PutativeMatches); // Draw correspondences after Nearest Neighbor ratio filter const bool bVertical = true; Matches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), vec_PutativeMatches, "03_Matches.svg", bVertical ); } // Fundamental geometry filtering of putative matches { //A. get back interest point and send it to the robust estimation framework Mat xL(2, vec_PutativeMatches.size()); Mat xR(2, vec_PutativeMatches.size()); for (size_t k = 0; k < vec_PutativeMatches.size(); ++k) { const PointFeature & imaL = featsL[vec_PutativeMatches[k].i_]; const PointFeature & imaR = featsR[vec_PutativeMatches[k].j_]; xL.col(k) = imaL.coords().cast<double>(); xR.col(k) = imaR.coords().cast<double>(); } //-- Fundamental robust estimation std::vector<uint32_t> vec_inliers; using KernelType = ACKernelAdaptor< openMVG::fundamental::kernel::SevenPointSolver, openMVG::fundamental::kernel::SymmetricEpipolarDistanceError, UnnormalizerT, Mat3>; KernelType kernel( xL, imageL.Width(), imageL.Height(), xR, imageR.Width(), imageR.Height(), true); // configure as point to line error model. Mat3 F; const std::pair<double,double> ACRansacOut = ACRANSAC(kernel, vec_inliers, 1024, &F, Square(4.0), // Upper bound of authorized threshold true); const double & thresholdF = ACRansacOut.first; // Check the fundamental support some point to be considered as valid if (vec_inliers.size() > KernelType::MINIMUM_SAMPLES *2.5) { std::cout << "\nFound a fundamental under the confidence threshold of: " << thresholdF << " pixels\n\twith: " << vec_inliers.size() << " inliers" << " from: " << vec_PutativeMatches.size() << " putatives correspondences" << std::endl; //Show fundamental validated point and compute residuals const bool bVertical = true; InlierMatches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), vec_PutativeMatches, vec_inliers, "04_ACRansacFundamental.svg", bVertical ); std::vector<double> vec_residuals(vec_inliers.size(), 0.0); for ( size_t i = 0; i < vec_inliers.size(); ++i) { const SIOPointFeature & LL = regionsL->Features()[vec_PutativeMatches[vec_inliers[i]].i_]; const SIOPointFeature & RR = regionsR->Features()[vec_PutativeMatches[vec_inliers[i]].j_]; // residual computation vec_residuals[i] = std::sqrt(KernelType::ErrorT::Error(F, LL.coords().cast<double>(), RR.coords().cast<double>())); } // Display some statistics of reprojection errors float dMin, dMax, dMean, dMedian; minMaxMeanMedian<float>(vec_residuals.cbegin(), vec_residuals.cend(), dMin, dMax, dMean, dMedian); std::cout << std::endl << "Fundamental matrix estimation, residuals statistics:" << "\n" << "\t-- Residual min:\t" << dMin << std::endl << "\t-- Residual median:\t" << dMedian << std::endl << "\t-- Residual max:\t " << dMax << std::endl << "\t-- Residual mean:\t " << dMean << std::endl; } else { std::cout << "ACRANSAC was unable to estimate a rigid fundamental" << std::endl; } } return EXIT_SUCCESS; }
6,842
C++
.cpp
166
35.271084
98
0.668672
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,862
robust_estimation_tutorial_homography.cpp
openMVG_openMVG/src/openMVG_Samples/multiview_robust_estimation_tutorial/robust_estimation_tutorial_homography.cpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2016 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/image/image_io.hpp" #include "openMVG/image/image_concat.hpp" #include "openMVG/features/feature.hpp" #include "openMVG/features/sift/SIFT_Anatomy_Image_Describer.hpp" #include "openMVG/features/svg_features.hpp" #include "openMVG/matching/regions_matcher.hpp" #include "openMVG/matching/svg_matches.hpp" // Robust estimation includes //-- //-- Homography estimator #include "openMVG/multiview/solver_homography_kernel.hpp" //-- //- Fitting metric helper (measure the fitting error between the datum and a Model) #include "openMVG/robust_estimation/score_evaluator.hpp" //-- //- MaxConsensus #include "openMVG/robust_estimation/robust_estimator_MaxConsensus.hpp" //- Ransac #include "openMVG/robust_estimation/robust_estimator_Ransac.hpp" //- LMeds #include "openMVG/robust_estimation/robust_estimator_LMeds.hpp" //- ACRANSAC #include "openMVG/robust_estimation/robust_estimator_ACRansac.hpp" #include "openMVG/robust_estimation/robust_estimator_ACRansacKernelAdaptator.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include "openMVG/vector_graphics/svgDrawer.hpp" #include <string> #include <iostream> using namespace openMVG; using namespace openMVG::image; using namespace openMVG::features; using namespace openMVG::matching; using namespace openMVG::robust; using namespace svg; //- Helper function // Display a visual report of the inliers void display_info ( const std::string & jpg_filenameL, const Image<unsigned char> & imageL, const PointFeatures & featsL, const std::string & jpg_filenameR, const Image<unsigned char> & imageR, const PointFeatures & featsR, const IndMatches & vec_PutativeMatches, const Mat3 &H, const std::vector<uint32_t> & vec_inliers, const std::string & sMethod ); int main() { Image<RGBColor> image; const std::string jpg_filenameL = stlplus::folder_up(std::string(THIS_SOURCE_DIR)) + "/imageData/StanfordMobileVisualSearch/Ace_0.png"; const std::string jpg_filenameR = stlplus::folder_up(std::string(THIS_SOURCE_DIR)) + "/imageData/StanfordMobileVisualSearch/Ace_1.png"; Image<unsigned char> imageL, imageR; ReadImage(jpg_filenameL.c_str(), &imageL); ReadImage(jpg_filenameR.c_str(), &imageR); //-- // Detect regions thanks to an image_describer //-- std::unique_ptr<Image_describer> image_describer (new SIFT_Anatomy_Image_describer(SIFT_Anatomy_Image_describer::Params(-1))); std::map<IndexT, std::unique_ptr<features::Regions>> regions_perImage; image_describer->Describe(imageL, regions_perImage[0]); image_describer->Describe(imageR, regions_perImage[1]); const SIFT_Regions* regionsL = dynamic_cast<SIFT_Regions*>(regions_perImage.at(0).get()); const SIFT_Regions* regionsR = dynamic_cast<SIFT_Regions*>(regions_perImage.at(1).get()); const PointFeatures featsL = regions_perImage.at(0)->GetRegionsPositions(), featsR = regions_perImage.at(1)->GetRegionsPositions(); // Show both images side by side { Image<unsigned char> concat; ConcatH(imageL, imageR, concat); std::string out_filename = "01_concat.jpg"; WriteImage(out_filename.c_str(), concat); } //- Draw features on the two image (side by side) { Features2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->Features(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->Features(), "02_features.svg" ); } std::vector<IndMatch> vec_PutativeMatches; //-- Perform matching -> find Nearest neighbor, filtered with Distance ratio { // Find corresponding points matching::DistanceRatioMatch( 0.8, matching::BRUTE_FORCE_L2, *regions_perImage.at(0).get(), *regions_perImage.at(1).get(), vec_PutativeMatches); // Draw correspondences after Nearest Neighbor ratio filter const bool bVertical = true; Matches2SVG ( jpg_filenameL, {imageL.Width(), imageL.Height()}, regionsL->GetRegionsPositions(), jpg_filenameR, {imageR.Width(), imageR.Height()}, regionsR->GetRegionsPositions(), vec_PutativeMatches, "03_Matches.svg", bVertical ); } //--- // Homography geometry filtering of putative matches // - Show how to use the robust_estimation framework with different robust_estimator methods. //--- // First we list the SIFT photometric corresponding points to Mat arrays (The datum). Mat xL(2, vec_PutativeMatches.size()); Mat xR(2, vec_PutativeMatches.size()); for (size_t k = 0; k < vec_PutativeMatches.size(); ++k) { // For each correspondence, add the Right & Left feature point positions const PointFeature & imaL = featsL[vec_PutativeMatches[k].i_]; const PointFeature & imaR = featsR[vec_PutativeMatches[k].j_]; xL.col(k) = imaL.coords().cast<double>(); xR.col(k) = imaR.coords().cast<double>(); } // Then we use a robust_estimator to find if a model can be fitted in the defined datum //-- //-- Max Consensus //- Return the Model that have the most of inliers //- Perform all the iterations (no early exit) { std::cout << "----------------------------------\n" << "MAXConsensus -- Robust estimation \n" << "----------------------------------\n"; // Define the Homography Kernel using KernelType = homography::kernel::UnnormalizedKernel; KernelType kernel(xL, xR); // The Model type Mat3 H; // The inlier list std::vector<uint32_t> vec_inliers; H = MaxConsensus ( kernel, // The Kernel (embed the correspondences, the Model Solver & the fitting metric. ScorerEvaluator<KernelType>(4.0), // Upper bound of the tolerated error for the inliers &vec_inliers, // Inlier list 1024 // max_iteration count ); display_info( jpg_filenameL, imageL, featsL, jpg_filenameR, imageR, featsR, vec_PutativeMatches, H, vec_inliers, "MAXConsensus"); } //-- //-- Ransac //- Return the Model that have the most of inliers //- Remaining iteration count can be decreased if meaningful models are found { std::cout << "----------------------------------\n" << "RANSAC -- Robust estimation \n" << "----------------------------------\n"; // Define the Homography Kernel using KernelType = homography::kernel::UnnormalizedKernel; KernelType kernel(xL, xR); // The Model type Mat3 H; // The inlier list std::vector<uint32_t> vec_inliers; // Inlier count size_t inlier_count = 0; H = RANSAC ( kernel, // The Kernel (embed the correspondences, the Model Solver & the fitting metric. ScorerEvaluator<KernelType>(4.0), // Upper bound of the tolerated error for the inliers &vec_inliers, // Inlier list &inlier_count // Inlier count ); display_info( jpg_filenameL, imageL, featsL, jpg_filenameR, imageR, featsR, vec_PutativeMatches, H, vec_inliers, "RANSAC"); } //-- //-- LMeds //- Return the Model that have the most of inliers //- Minimize the median of the error (no input precision to provide) { std::cout << "----------------------------------\n" << "LMEDS -- Robust estimation \n" << "----------------------------------\n"; // Define the Homography Kernel using KernelType = homography::kernel::UnnormalizedKernel; KernelType kernel(xL, xR); // The Model type Mat3 H; double lmeds_threshold = 0.0; LeastMedianOfSquares ( kernel, // The Kernel (embed the correspondences, the Model Solver & the fitting metric. &H, // Update model &lmeds_threshold // Upper bound of the tolerated error for the inliers ); // List the inliers std::vector<uint32_t> vec_inliers; for (int i = 0; i < xL.cols(); ++i) { const double residual_error = std::sqrt(kernel.Error(i, H)); if (residual_error < lmeds_threshold) vec_inliers.push_back(i); } display_info( jpg_filenameL, imageL, featsL, jpg_filenameR, imageR, featsR, vec_PutativeMatches, H, vec_inliers, "LMEDS"); } //-- //-- AContrario Ransac //- Apriori inlier/outlier error threshold is only an option. //- The robust estimator finds the best meaningful model and its associated precision { std::cout << "----------------------------------\n" << "ACRansac -- Robust estimation \n" << "----------------------------------\n"; // Define the AContrario Kernel adaptor for the Homography Model using KernelType = ACKernelAdaptor< openMVG::homography::kernel::FourPointSolver, openMVG::homography::kernel::AsymmetricError, UnnormalizerI, Mat3>; KernelType kernel( xL, imageL.Width(), imageL.Height(), xR, imageR.Width(), imageR.Height(), false); // configure as point to point error model. // The Model type Mat3 H; // The inlier list std::vector<uint32_t> vec_inliers; // Call the Robust Estimator on the KERNEL const std::pair<double,double> ACRansacOut = // Return the precision & the associated NFA ACRANSAC( kernel, // The Kernel (embed the correspondences, the Model Solver & the fitting metric. vec_inliers, // The inlier list 1024, // Max iteration count (it can be less if a meaningful is found at the first iterations) &H, // Returned model std::numeric_limits<double>::infinity(), // No apriori Threshold false // Verbose to console ); const double & thresholdH = ACRansacOut.first; std::cout << "AContrario Upperbound error estimation is: " << thresholdH << std::endl; display_info( jpg_filenameL, imageL, featsL, jpg_filenameR, imageR, featsR, vec_PutativeMatches, H, vec_inliers, "ACRansac"); } return EXIT_SUCCESS; } void display_info ( const std::string & jpg_filenameL, const Image<unsigned char> & imageL, const PointFeatures & featsL, const std::string & jpg_filenameR, const Image<unsigned char> & imageR, const PointFeatures & featsR, const IndMatches & vec_PutativeMatches, const Mat3 &H, const std::vector<uint32_t> & vec_inliers, const std::string & sMethod ) { std::cout << "\nFound a homography with: " << vec_inliers.size() << " inliers" << " from: " << vec_PutativeMatches.size() << " putatives correspondences" << std::endl; //Show homography validated point and compute residuals std::vector<double> vec_residuals(vec_inliers.size(), 0.0); svgDrawer svgStream( imageL.Width() + imageR.Width(), std::max(imageL.Height(), imageR.Height())); svgStream << svg::drawImage(jpg_filenameL, imageL.Width(), imageL.Height()); svgStream << svg::drawImage(jpg_filenameR, imageR.Width(), imageR.Height(), imageL.Width()); for ( size_t i = 0; i < vec_inliers.size(); ++i) { const PointFeature & L = featsL[vec_PutativeMatches[vec_inliers[i]].i_]; const PointFeature & R = featsR[vec_PutativeMatches[vec_inliers[i]].j_]; svgStream << svg::drawLine(L.x(), L.y(), R.x()+imageL.Width(), R.y(), svgAttributes().stroke("green", 2.0)); svgStream << svg::drawCircle(L.x(), L.y(), 5, svgAttributes().stroke("yellow", 2.0)); svgStream << svg::drawCircle(R.x()+imageL.Width(), R.y(), 5,svgAttributes().stroke("yellow", 2.0)); // residual computation using KernelType = homography::kernel::UnnormalizedKernel; vec_residuals[i] = std::sqrt( KernelType::ErrorT::Error(H, L.coords().cast<double>(), R.coords().cast<double>())); } std::ostringstream os; os << sMethod << "_robust_fitting.svg"; std::ofstream svgFile( os.str().c_str() ); svgFile << svgStream.closeSvgFile().str(); svgFile.close(); // Display some statistics of reprojection errors double dMin, dMax, dMean, dMedian; minMaxMeanMedian<double>(vec_residuals.begin(), vec_residuals.end(), dMin, dMax, dMean, dMedian); std::cout << std::endl << "Homography matrix estimation, residuals statistics:" << "\n" << "\t-- Residual min:\t" << dMin << std::endl << "\t-- Residual median:\t" << dMedian << std::endl << "\t-- Residual max:\t " << dMax << std::endl << "\t-- Residual mean:\t " << dMean << std::endl; }
12,663
C++
.cpp
330
33.7
112
0.665338
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,864
undistoBrown.cpp
openMVG_openMVG/src/openMVG_Samples/cameras_undisto_Brown/undistoBrown.cpp
// Copyright (c) 2013 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/cameras/Camera_Pinhole_Radial.hpp" #include "openMVG/cameras/Camera_undistort_image.hpp" #include "openMVG/image/image_io.hpp" #include "openMVG/system/loggerprogress.hpp" #include "third_party/cmdLine/cmdLine.h" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <cstdlib> #include <iostream> #include <string> using namespace openMVG; using namespace openMVG::cameras; using namespace openMVG::image; int main(int argc, char **argv) { CmdLine cmd; std::string sPath; std::string sOutPath; // Temp storage for the Brown's distortion model Vec2 c; // distortion center Vec3 k; // distortion factors double f; // Focal std::string suffix = "JPG"; cmd.add( make_option('i', sPath, "imadir") ); cmd.add( make_option('o', sOutPath, "outdir") ); cmd.add( make_option('a', c(0), "cx") ); cmd.add( make_option('b', c(1), "cy") ); cmd.add( make_option('c', k(0), "k1") ); cmd.add( make_option('d', k(1), "k2") ); cmd.add( make_option('e', k(2), "k3") ); cmd.add( make_option('f', f, "focal") ); cmd.add( make_option('s', suffix, "suffix") ); try { if (argc == 1) throw std::string("Invalid command line parameter."); cmd.process(argc, argv); } catch (const std::string& s) { std::cerr << "Usage: " << argv[0] << ' ' << "[-i|--imadir - Input path]\n" << "[-o|--outdir - path for the undistorted JPG files]\n" << "[-f|--focal - focal length]\n" << "[-s|--suffix - Suffix of the input files. (default: JPG)]\n" << std::endl; std::cerr << s << std::endl; return EXIT_FAILURE; } if (sOutPath == sPath) { std::cerr << "Input and Ouput path are set to the same value" << std::endl; return EXIT_FAILURE; } if (!stlplus::folder_exists(sOutPath)) stlplus::folder_create(sOutPath); std::cout << "Used Brown's distortion model values: \n" << " Distortion center: " << c.transpose() << "\n" << " Distortion coefficients (K1,K2,K3): " << k.transpose() << "\n" << " Distortion focal: " << f << std::endl; const std::vector<std::string> vec_fileNames = stlplus::folder_wildcard(sPath, "*."+suffix, false, true); std::cout << "\nLocated " << vec_fileNames.size() << " files in " << sPath << " with suffix " << suffix; Image<unsigned char > imageGreyIn, imageGreyU; Image<RGBColor> imageRGBIn, imageRGBU; Image<RGBAColor> imageRGBAIn, imageRGBAU; system::LoggerProgress my_progress_bar( vec_fileNames.size() ); for (size_t j = 0; j < vec_fileNames.size(); ++j, ++my_progress_bar) { //read the depth int w,h,depth; std::vector<unsigned char> tmp_vec; const std::string sOutFileName = stlplus::create_filespec(sOutPath, stlplus::basename_part(vec_fileNames[j]), "png"); const std::string sInFileName = stlplus::create_filespec(sPath, stlplus::filename_part(vec_fileNames[j])); const int res = ReadImage(sInFileName.c_str(), &tmp_vec, &w, &h, &depth); const Pinhole_Intrinsic_Radial_K3 cam(w, h, f, c(0), c(1), k(0), k(1), k(2)); if (res == 1) { switch (depth) { case 1: //Greyscale { imageGreyIn = Eigen::Map<Image<unsigned char>::Base>(&tmp_vec[0], h, w); UndistortImage(imageGreyIn, &cam, imageGreyU); WriteImage(sOutFileName.c_str(), imageGreyU); break; } case 3: //RGB { imageRGBIn = Eigen::Map<Image<RGBColor>::Base>((RGBColor*) &tmp_vec[0], h, w); UndistortImage(imageRGBIn, &cam, imageRGBU); WriteImage(sOutFileName.c_str(), imageRGBU); break; } case 4: //RGBA { imageRGBAIn = Eigen::Map<Image<RGBAColor>::Base>((RGBAColor*) &tmp_vec[0], h, w); UndistortImage(imageRGBAIn, &cam, imageRGBAU); WriteImage(sOutFileName.c_str(), imageRGBAU); break; } } }//end if res==1 else { std::cerr << "\nThe image contains " << depth << "layers. This depth is not supported!\n"; } } //end loop for each file return EXIT_SUCCESS; }
4,384
C++
.cpp
113
33.353982
96
0.619619
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
27,114
QImageInterface.cc
openMVG_openMVG/src/openMVG_Samples/image_undistort_gui/QImageInterface.cc
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 Romuald Perrot. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "QImageInterface.hh" #include <algorithm> #include <QRgb> #include <QVector> namespace image_undistort_gui { /** * @brief Build a QImage from an openMVG (RGB) image * @param img Input image * @return a QImage corresponding to the input image * @note this makes a deep copy of the image */ QImage openMVGImageToQImage( const openMVG::image::Image<openMVG::image::RGBColor> &img ) { const int bytePerRow = img.Width() * sizeof( openMVG::image::RGBColor ); QImage tmp( reinterpret_cast<const unsigned char *>( img.data() ), img.Width(), img.Height(), bytePerRow, QImage::Format_RGB888 ); // Make a deep copy return tmp.copy(); } /** * @brief Build a QImage from an openMVG (grayscale) image * @param img Input image * @return a QImage corresponding to the input image * @note this makes a deep copy of the image */ QImage openMVGImageToQImage( const openMVG::image::Image<unsigned char> &img ) { QImage tmp( reinterpret_cast<const unsigned char *>( img.data() ), img.Width(), img.Height(), QImage::Format_Indexed8 ); QVector<QRgb> colors( 256 ); for ( int i = 0; i < 256; ++i ) { colors[ i ] = qRgb(i, i, i); } tmp.setColorCount( 256 ); tmp.setColorTable( colors ); // Make a deep copy return std::move(tmp); } /** * @brief Convert a QImage to an openMVG image * @param img Input image * @return openMVG image corresponding to this image * @note this makes a deep copy */ openMVG::image::Image<openMVG::image::RGBColor> QImageToOpenMVGImage( const QImage &img ) { openMVG::image::Image<openMVG::image::RGBColor> res( img.width(), img.height() ); const QImage tmp = img.convertToFormat( QImage::Format_RGB888 ); // Make a deep copy std::copy( tmp.bits(), tmp.bits() + tmp.byteCount(), reinterpret_cast<unsigned char *>( res.data() ) ); return res; } } // namespace image_undistort_gui
2,192
C++
.cc
58
35.327586
132
0.708353
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
27,116
MainWindow.cc
openMVG_openMVG/src/openMVG_Samples/image_undistort_gui/MainWindow.cc
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 Romuald Perrot. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "MainWindow.hh" #include <iostream> #include "openMVG/cameras/Camera_undistort_image.hpp" #include "openMVG/cameras/Camera_Pinhole_Brown.hpp" #include "openMVG/cameras/Camera_Pinhole_Fisheye.hpp" #include "openMVG/cameras/Camera_Pinhole_Radial.hpp" #include "openMVG/image/image_io.hpp" #include "QImageInterface.hh" #include <QCoreApplication> #include <QDir> #include <QFileDialog> #include <QGridLayout> #include <QGroupBox> #include <QMenuBar> namespace image_undistort_gui { const int MainWindow::STATE_INITIAL = 0; const int MainWindow::STATE_HAS_INPUT = 1; const int MainWindow::STATE_HAS_COMPUTED_DISTORTION = 2; /** * @brief Constructor * @param parent Parent widget of this window */ MainWindow::MainWindow( QWidget *parent ) : QMainWindow( parent ), m_current_state( STATE_INITIAL ) { BuildInterface(); BuildMenus(); MakeConnections(); resize( 1024, 768 ); setWindowTitle( "ImageUndistort" ); UpdateInterface(); } /** * @brief Action to be executed when user want to open an image */ void MainWindow::onOpenImage( void ) { QString fileName = QFileDialog::getOpenFileName( this, tr( "Open File" ), QDir::homePath(), tr( "Images (*.png *.jpg *.tiff)" ) ); if ( !( fileName.isNull() || fileName.isEmpty() ) ) { QImage tmp( fileName ); m_inputImage = QImageToOpenMVGImage( tmp ); QPixmap pix = QPixmap::fromImage( tmp ); m_scene_old->clear(); m_scene_old->addPixmap( pix ); m_view_old->fitInView( m_scene_old->itemsBoundingRect(), Qt::KeepAspectRatio ); m_scene_new->clear(); const double w = m_inputImage.Width(); const double h = m_inputImage.Height(); m_ppx->setValue( w / 2.0 ); m_ppy->setValue( h / 2.0 ); m_fov_spin->setValue( 1.1 * std::max( w, h ) ); m_current_state = STATE_HAS_INPUT; UpdateInterface(); } } /** * @brief Action to be executed when user want to undistort an image */ void MainWindow::onProcessImage( void ) { if ( m_inputImage.Width() > 0 && m_inputImage.Height() > 0 ) { openMVG::cameras::IntrinsicBase *intrin = nullptr; const int w = m_inputImage.Width(); const int h = m_inputImage.Height(); const double fov = m_fov_spin->value(); const double ppx = m_ppx->value(); const double ppy = m_ppy->value(); const double k1 = m_k1->value(); const double k2 = m_k2->value(); const double k3 = m_k3->value(); const double k4 = m_k4->value(); const double t1 = m_t1->value(); const double t2 = m_t2->value(); switch ( m_intrinsic_type->currentIndex() ) { case 0: { intrin = new openMVG::cameras::Pinhole_Intrinsic( w, h, fov, ppx, ppy ); break; } case 1: { intrin = new openMVG::cameras::Pinhole_Intrinsic_Radial_K1( w, h, fov, ppx, ppy, k1 ); break; } case 2: { intrin = new openMVG::cameras::Pinhole_Intrinsic_Radial_K3( w, h, fov, ppx, ppy, k1, k2, k3 ); break; } case 3: { intrin = new openMVG::cameras::Pinhole_Intrinsic_Brown_T2( w, h, fov, ppx, ppy, k1, k2, k3, t1, t2 ); break; } case 4: { intrin = new openMVG::cameras::Pinhole_Intrinsic_Fisheye( w, h, fov, ppx, ppy, k1, k2, k3, k4 ); break; } } openMVG::cameras::UndistortImageResized( m_inputImage, intrin, m_outputImage ); QImage tmp = openMVGImageToQImage( m_outputImage ); QPixmap pix = QPixmap::fromImage( tmp ); m_scene_new->clear(); m_scene_new->addPixmap( pix ); m_view_new->fitInView( m_scene_new->itemsBoundingRect(), Qt::KeepAspectRatio ); m_current_state = STATE_HAS_COMPUTED_DISTORTION; UpdateInterface(); } } /** * @brief Action to be executed when user want to export an undistorted image */ void MainWindow::onExportImage( void ) { QString fileName = QFileDialog::getSaveFileName( this, "Save image", QDir::homePath(), tr( "Images (*.png *.jpg *.tiff)" ) ); if ( !( fileName.isEmpty() || fileName.isNull() ) ) { const std::string name = fileName.toStdString(); openMVG::image::WriteImage( name.c_str(), m_outputImage ); } } /** * @brief Action to be executed when user select an intrinsic type */ void MainWindow::onSelectIntrinsicType( void ) { const int idx = m_intrinsic_type->currentIndex(); switch ( idx ) { case 0: { // No dist m_k1->setEnabled( false ); m_k2->setEnabled( false ); m_k3->setEnabled( false ); m_k4->setEnabled( false ); m_t1->setEnabled( false ); m_t2->setEnabled( false ); m_label_k1->setVisible( false ); m_k1->setVisible( false ); m_label_k2->setVisible( false ); m_k2->setVisible( false ); m_label_k3->setVisible( false ); m_k3->setVisible( false ); m_label_k4->setVisible( false ); m_k4->setVisible( false ); m_label_t1->setVisible( false ); m_t1->setVisible( false ); m_label_t2->setVisible( false ); m_t2->setVisible( false ); break; } case 1: { // R1 m_k1->setEnabled( true ); m_k2->setEnabled( false ); m_k3->setEnabled( false ); m_k4->setEnabled( false ); m_t1->setEnabled( false ); m_t2->setEnabled( false ); m_label_k1->setVisible( true ); m_k1->setVisible( true ); m_label_k2->setVisible( false ); m_k2->setVisible( false ); m_label_k3->setVisible( false ); m_k3->setVisible( false ); m_label_k4->setVisible( false ); m_k4->setVisible( false ); m_label_t1->setVisible( false ); m_t1->setVisible( false ); m_label_t2->setVisible( false ); m_t2->setVisible( false ); break; } case 2: { // R3 m_k1->setEnabled( true ); m_k2->setEnabled( true ); m_k3->setEnabled( true ); m_k4->setEnabled( false ); m_t1->setEnabled( false ); m_t2->setEnabled( false ); m_label_k1->setVisible( true ); m_k1->setVisible( true ); m_label_k2->setVisible( true ); m_k2->setVisible( true ); m_label_k3->setVisible( true ); m_k3->setVisible( true ); m_label_k4->setVisible( false ); m_k4->setVisible( false ); m_label_t1->setVisible( false ); m_t1->setVisible( false ); m_label_t2->setVisible( false ); m_t2->setVisible( false ); break; } case 3: { // Brown R3 - T2 m_k1->setEnabled( true ); m_k2->setEnabled( true ); m_k3->setEnabled( true ); m_k4->setEnabled( false ); m_t1->setEnabled( true ); m_t2->setEnabled( true ); m_label_k1->setVisible( true ); m_k1->setVisible( true ); m_label_k2->setVisible( true ); m_k2->setVisible( true ); m_label_k3->setVisible( true ); m_k3->setVisible( true ); m_label_k4->setVisible( false ); m_k4->setVisible( false ); m_label_t1->setVisible( true ); m_t1->setVisible( true ); m_label_t2->setVisible( true ); m_t2->setVisible( true ); break; } case 4: { // Fisheye R4 m_k1->setEnabled( true ); m_k2->setEnabled( true ); m_k3->setEnabled( true ); m_k4->setEnabled( true ); m_t1->setEnabled( false ); m_t2->setEnabled( false ); m_label_k1->setVisible( true ); m_k1->setVisible( true ); m_label_k2->setVisible( true ); m_k2->setVisible( true ); m_label_k3->setVisible( true ); m_k3->setVisible( true ); m_label_k4->setVisible( true ); m_k4->setVisible( true ); m_label_t1->setVisible( false ); m_t1->setVisible( false ); m_label_t2->setVisible( false ); m_t2->setVisible( false ); break; } } } /** * @brief Action to be executed when user check/uncheck the grid checkbox */ void MainWindow::onChangeCheckBox( void ) { if ( m_check_use_grid->isChecked() ) { BuildGrid(); m_scene_new->clear(); m_current_state = STATE_HAS_INPUT; } else { m_inputImage = openMVG::image::Image<openMVG::image::RGBColor>( 10, 10 ); m_scene_old->clear(); m_scene_new->clear(); m_current_state = STATE_INITIAL; } UpdateInterface(); } /** * @brief action to be executed when user select no distorsion menu item */ void MainWindow::onMenuSelectNoDist( void ) { m_intrinsic_type->setCurrentIndex( 0 ); UpdateInterface(); } /** * @brief action to be executed when user select radial 1 menu item */ void MainWindow::onMenuSelectRadial1( void ) { m_intrinsic_type->setCurrentIndex( 1 ); UpdateInterface(); } /** * @brief action to be executed when user select radial 3 menu item */ void MainWindow::onMenuSelectRadial3( void ) { m_intrinsic_type->setCurrentIndex( 2 ); UpdateInterface(); } /** * @brief action to be executed when user select brown menu item */ void MainWindow::onMenuSelectBrown( void ) { m_intrinsic_type->setCurrentIndex( 3 ); UpdateInterface(); } /** * @brief action to be executed when user select fisheye menu item */ void MainWindow::onMenuSelectFisheye( void ) { m_intrinsic_type->setCurrentIndex( 4 ); UpdateInterface(); } /** * @brief action to be executed when user select quit menu item */ void MainWindow::onQuit( void ) { QCoreApplication::quit(); } /** * @brief Fill intrinsic values in the combobox */ void MainWindow::FillIntrinsicTypes( void ) { m_intrinsic_type->addItem( "No distorsion" ); m_intrinsic_type->addItem( "Radial 1" ); m_intrinsic_type->addItem( "Radial 3" ); m_intrinsic_type->addItem( "Brown : Radial 3 - tangential 2" ); m_intrinsic_type->addItem( "Fisheye" ); } /** * @brief Build virtual image representing a regular grid */ void MainWindow::BuildGrid( void ) { int w = 1280; int h = 720; m_inputImage = openMVG::image::Image<openMVG::image::RGBColor>( w, h ); int nb_x = 16; int nb_y = 9; const double delta_x = w / nb_x; const double delta_y = h / nb_y; // Vertical lines for ( int i = 1; i < nb_x; ++i ) { const int x = i * delta_x; for ( int y = 0; y < h; ++y ) { m_inputImage( y, x - 1 ) = openMVG::image::RGBColor( 255, 255, 255 ); m_inputImage( y, x ) = openMVG::image::RGBColor( 255, 255, 255 ); m_inputImage( y, x + 1 ) = openMVG::image::RGBColor( 255, 255, 255 ); } } // Horizontal lines for ( int i = 1; i < nb_y; ++i ) { const int y = i * delta_y; for ( int x = 0; x < w; ++x ) { m_inputImage( y - 1, x ) = openMVG::image::RGBColor( 255, 255, 255 ); m_inputImage( y, x ) = openMVG::image::RGBColor( 255, 255, 255 ); m_inputImage( y + 1, x ) = openMVG::image::RGBColor( 255, 255, 255 ); } } QImage tmp = openMVGImageToQImage( m_inputImage ); m_scene_old->clear(); m_scene_old->addPixmap( QPixmap::fromImage( tmp ) ); m_view_old->fitInView( m_scene_old->itemsBoundingRect(), Qt::KeepAspectRatio ); m_ppx->setValue( w / 2 ); m_ppy->setValue( h / 2 ); m_fov_spin->setValue( 1.1 * std::max( w, h ) ); } /** * @brief update interface based on internal state */ void MainWindow::UpdateInterface( void ) { switch ( m_current_state ) { case STATE_INITIAL: { m_open_image->setEnabled( true ); m_process->setEnabled( false ); m_exportResult->setEnabled( false ); if ( m_process_act ) { m_process_act->setEnabled( false ); m_export_act->setEnabled( false ); } break; } case STATE_HAS_INPUT: { if ( m_check_use_grid->isChecked() ) { m_open_image->setEnabled( false ); m_open_image_act->setEnabled( false ); } else { m_open_image->setEnabled( true ); m_open_image_act->setEnabled( true ); } m_exportResult->setEnabled( false ); m_export_act->setEnabled( false ); m_process_act->setEnabled( true ); m_process->setEnabled( true ); break; } case STATE_HAS_COMPUTED_DISTORTION: { m_process->setEnabled( true ); m_exportResult->setEnabled( true ); m_process_act->setEnabled( true ); m_export_act->setEnabled( true ); break; } } if ( !m_fileMenu || !m_processMenu || !m_inputMenu ) return; switch ( m_intrinsic_type->currentIndex() ) { case 0: { m_no_dist_act->setChecked( true ); m_radial_k1_act->setChecked( false ); m_radial_k3_act->setChecked( false ); m_brown_act->setChecked( false ); m_fisheye_act->setChecked( false ); break; } case 1: { m_no_dist_act->setChecked( false ); m_radial_k1_act->setChecked( true ); m_radial_k3_act->setChecked( false ); m_brown_act->setChecked( false ); m_fisheye_act->setChecked( false ); break; } case 2: { m_no_dist_act->setChecked( false ); m_radial_k1_act->setChecked( false ); m_radial_k3_act->setChecked( true ); m_brown_act->setChecked( false ); m_fisheye_act->setChecked( false ); break; } case 3: { m_no_dist_act->setChecked( false ); m_radial_k1_act->setChecked( false ); m_radial_k3_act->setChecked( false ); m_brown_act->setChecked( true ); m_fisheye_act->setChecked( false ); break; } case 4: { m_no_dist_act->setChecked( false ); m_radial_k1_act->setChecked( false ); m_radial_k3_act->setChecked( false ); m_brown_act->setChecked( false ); m_fisheye_act->setChecked( true ); break; } } } /** * @brief Build Interface widgets */ void MainWindow::BuildInterface() { QGroupBox *inputGrp = new QGroupBox( "Input" ); QGridLayout *inputLayout = new QGridLayout; m_open_image = new QPushButton( "Open image" ); m_check_use_grid = new QCheckBox( "Use grid" ); inputLayout->addWidget( m_open_image, 0, 0 ); inputLayout->addWidget( m_check_use_grid, 0, 1 ); inputGrp->setLayout( inputLayout ); QGroupBox *intrinsicGrp = new QGroupBox( "Intrinsic" ); QGridLayout *intrinsicLayout = new QGridLayout; m_intrinsic_label = new QLabel( "Type" ); m_intrinsic_type = new QComboBox; QGroupBox *pinholeGrp = new QGroupBox( "Pinhole" ); QGridLayout *pinholeLayout = new QGridLayout; m_label_fov = new QLabel( "Focal" ); m_fov_spin = new QDoubleSpinBox; m_fov_spin->setMaximum( 100000.0 ); m_label_ppx = new QLabel( "Princ. P. X" ); m_ppx = new QDoubleSpinBox; m_ppx->setMaximum( 50000.0 ); m_ppx->setMinimum( -50000.0 ); m_label_ppy = new QLabel( "Princ. P. Y" ); m_ppy = new QDoubleSpinBox; m_ppy->setMaximum( 50000.0 ); m_ppy->setMinimum( -50000.0 ); pinholeLayout->addWidget( m_label_fov, 0, 0, Qt::AlignRight ); pinholeLayout->addWidget( m_fov_spin, 0, 1 ); pinholeLayout->addWidget( m_label_ppx, 0, 2, Qt::AlignRight ); pinholeLayout->addWidget( m_ppx, 0, 3 ); pinholeLayout->addWidget( m_label_ppy, 0, 4, Qt::AlignRight ); pinholeLayout->addWidget( m_ppy, 0, 5 ); pinholeGrp->setLayout( pinholeLayout ); QGroupBox *distGrp = new QGroupBox( "Distorsion" ); QGridLayout *distLayout = new QGridLayout; m_label_k1 = new QLabel( "K1" ); m_k1 = new QDoubleSpinBox; m_k1->setDecimals( 6 ); m_k1->setMaximum( 10000.0 ); m_k1->setMinimum( -10000.0 ); m_label_k2 = new QLabel( "K2" ); m_k2 = new QDoubleSpinBox; m_k2->setDecimals( 6 ); m_k2->setMaximum( 10000.0 ); m_k2->setMinimum( -10000.0 ); m_label_k3 = new QLabel( "K3" ); m_k3 = new QDoubleSpinBox; m_k3->setDecimals( 6 ); m_k3->setMaximum( 10000.0 ); m_k3->setMinimum( -10000.0 ); m_label_k4 = new QLabel( "K4" ); m_k4 = new QDoubleSpinBox; m_k4->setDecimals( 6 ); m_k4->setMaximum( 10000.0 ); m_k4->setMinimum( -10000.0 ); m_label_t1 = new QLabel( "T1" ); m_t1 = new QDoubleSpinBox; m_t1->setDecimals( 6 ); m_t1->setMaximum( 10000.0 ); m_t1->setMinimum( -10000.0 ); m_label_t2 = new QLabel( "T2" ); m_t2 = new QDoubleSpinBox; m_t2->setDecimals( 6 ); m_t2->setMaximum( 10000.0 ); m_t2->setMinimum( -10000.0 ); distLayout->addWidget( m_label_k1, 0, 0, Qt::AlignRight ); distLayout->addWidget( m_k1, 0, 1 ); distLayout->addWidget( m_label_k2, 0, 2, Qt::AlignRight ); distLayout->addWidget( m_k2, 0, 3 ); distLayout->addWidget( m_label_k3, 0, 4, Qt::AlignRight ); distLayout->addWidget( m_k3, 0, 5 ); distLayout->addWidget( m_label_k4, 0, 6, Qt::AlignRight ); distLayout->addWidget( m_k4, 0, 7 ); distLayout->addWidget( m_label_t1, 1, 0, Qt::AlignRight ); distLayout->addWidget( m_t1, 1, 1 ); distLayout->addWidget( m_label_t2, 1, 2, Qt::AlignRight ); distLayout->addWidget( m_t2, 1, 3 ); distGrp->setLayout( distLayout ); intrinsicLayout->addWidget( m_intrinsic_label, 0, 0 ); intrinsicLayout->addWidget( m_intrinsic_type, 0, 1 ); intrinsicLayout->addWidget( pinholeGrp, 1, 0, 1, 2 ); intrinsicLayout->addWidget( distGrp, 2, 0, 1, 2 ); intrinsicGrp->setLayout( intrinsicLayout ); // Processing QGroupBox *processGrp = new QGroupBox( "Processing" ); QHBoxLayout *layoutProcess = new QHBoxLayout; m_process = new QPushButton( "Undistort" ); m_exportResult = new QPushButton( "Export" ); layoutProcess->addWidget( m_process ); layoutProcess->addWidget( m_exportResult ); processGrp->setLayout( layoutProcess ); // Result QGroupBox *resultGrp = new QGroupBox( "Images" ); m_scene_new = new QGraphicsScene; m_scene_old = new QGraphicsScene; m_view_new = new QGraphicsView( m_scene_new ); m_view_old = new QGraphicsView( m_scene_old ); QHBoxLayout *resultLayout = new QHBoxLayout; resultLayout->addWidget( m_view_old ); resultLayout->addWidget( m_view_new ); QVBoxLayout *dummyResultLayout = new QVBoxLayout; dummyResultLayout->addLayout( resultLayout ); resultGrp->setLayout( dummyResultLayout ); QWidget *dummy = new QWidget; QVBoxLayout *dummyLayout = new QVBoxLayout; dummyLayout->addWidget( inputGrp ); dummyLayout->addWidget( intrinsicGrp ); dummyLayout->addWidget( processGrp ); dummyLayout->addWidget( resultGrp ); dummy->setLayout( dummyLayout ); setCentralWidget( dummy ); FillIntrinsicTypes(); onSelectIntrinsicType(); } /** * @brief Create menus items */ void MainWindow::BuildMenus() { m_fileMenu = new QMenu( "File" ); m_quit_act = m_fileMenu->addAction( "Quit" ); m_quit_act->setShortcut( QKeySequence::Quit ); m_fileMenu->addAction( m_quit_act ); m_inputMenu = new QMenu( "Input" ); m_open_image_act = m_fileMenu->addAction( "Open image" ); m_open_image_act->setShortcut( QKeySequence::Open ); m_use_grid_act = m_fileMenu->addAction( "Use grid" ); m_inputMenu->addAction( m_open_image_act ); m_inputMenu->addAction( m_use_grid_act ); m_intrinsicMenu = new QMenu( "Intrinsic Type" ); m_no_dist_act = m_fileMenu->addAction( "No distortion" ); m_no_dist_act->setCheckable( true ); m_radial_k1_act = m_fileMenu->addAction( "Radial 1" ); m_radial_k1_act->setCheckable( true ); m_radial_k3_act = m_fileMenu->addAction( "Radial 3" ); m_radial_k3_act->setCheckable( true ); m_brown_act = m_fileMenu->addAction( "Brown (3R-2T)" ); m_brown_act->setCheckable( true ); m_fisheye_act = m_fileMenu->addAction( "Fisheye" ); m_fisheye_act->setCheckable( true ); m_intrinsicMenu->addAction( m_no_dist_act ); m_intrinsicMenu->addAction( m_radial_k1_act ); m_intrinsicMenu->addAction( m_radial_k3_act ); m_intrinsicMenu->addAction( m_brown_act ); m_intrinsicMenu->addAction( m_fisheye_act ); m_processMenu = new QMenu( "Processing" ); m_process_act = m_fileMenu->addAction( "Undistort" ); m_export_act = m_fileMenu->addAction( "Export image" ); m_processMenu->addAction( m_process_act ); m_processMenu->addAction( m_export_act ); QMenuBar *mbar = this->menuBar(); mbar->addMenu( m_fileMenu ); mbar->addMenu( m_inputMenu ); mbar->addMenu( m_intrinsicMenu ); mbar->addMenu( m_processMenu ); } /** * @brief Make connections between interface items and slots */ void MainWindow::MakeConnections() { connect( m_open_image, SIGNAL( clicked() ), this, SLOT( onOpenImage() ) ); connect( m_process, SIGNAL( clicked() ), this, SLOT( onProcessImage() ) ); connect( m_exportResult, SIGNAL( clicked() ), this, SLOT( onExportImage() ) ); connect( m_intrinsic_type, SIGNAL( currentIndexChanged( int ) ), this, SLOT( onSelectIntrinsicType() ) ); connect( m_check_use_grid, SIGNAL( stateChanged( int ) ), this, SLOT( onChangeCheckBox() ) ); connect( m_open_image_act, SIGNAL( triggered() ), this, SLOT( onOpenImage() ) ); connect( m_process_act, SIGNAL( triggered() ), this, SLOT( onProcessImage() ) ); connect( m_export_act, SIGNAL( triggered() ), this, SLOT( onExportImage() ) ); connect( m_quit_act, SIGNAL( triggered() ), this, SLOT( onQuit() ) ); connect( m_no_dist_act, SIGNAL( triggered() ), this, SLOT( onMenuSelectNoDist() ) ); connect( m_radial_k1_act, SIGNAL( triggered() ), this, SLOT( onMenuSelectRadial1() ) ); connect( m_radial_k3_act, SIGNAL( triggered() ), this, SLOT( onMenuSelectRadial3() ) ); connect( m_brown_act, SIGNAL( triggered() ), this, SLOT( onMenuSelectBrown() ) ); connect( m_fisheye_act, SIGNAL( triggered() ), this, SLOT( onMenuSelectFisheye() ) ); } } // namespace image_undistort_gui
21,465
C++
.cc
655
28.775573
107
0.648545
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
27,119
types.hpp
openMVG_openMVG/src/openMVG/types.hpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_TYPES_HPP #define OPENMVG_TYPES_HPP #include <algorithm> #include <cstdint> #include <functional> #include <limits> #include <map> #include <set> #include <unordered_map> #include <utility> #include <vector> #include "openMVG/stl/hash.hpp" namespace std { template<typename T1, typename T2> struct hash<std::pair<T1, T2>> { std::size_t operator()(std::pair<T1, T2> const &p) const { std::size_t seed1(0); stl::hash_combine(seed1, p.first); stl::hash_combine(seed1, p.second); std::size_t seed2(0); stl::hash_combine(seed2, p.second); stl::hash_combine(seed2, p.first); return std::min(seed1, seed2); } }; } /** * @brief Main namespace of openMVG API */ namespace openMVG { /// Portable type used to store an index using IndexT = uint32_t; /// Portable value used to save an undefined index value static const IndexT UndefinedIndexT = std::numeric_limits<IndexT>::max(); /// Standard Pair of IndexT using Pair = std::pair<IndexT, IndexT>; /// Set of Pair using Pair_Set = std::set<Pair>; /// Vector of Pair using Pair_Vec = std::vector<Pair>; /** * @brief Standard Hash_Map class * @tparam K type of the keys * @tparam V type of the values */ template<typename Key, typename Value> using Hash_Map = std::unordered_map<Key, Value>; } // namespace openMVG #endif // OPENMVG_TYPES_HPP
1,686
C++
.h
55
28.345455
76
0.713313
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
27,124
graph_stats.hpp
openMVG_openMVG/src/openMVG/graph/graph_stats.hpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2019 openMVG authors. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_GRAPH_GRAPH_STATS_HPP #define OPENMVG_GRAPH_GRAPH_STATS_HPP #include "openMVG/graph/connectedComponent.hpp" #include "openMVG/graph/graph_builder.hpp" #include "openMVG/numeric/numeric.h" namespace openMVG { namespace graph { /// Export graph statistics to the console: /// - number of node /// - number of cc /// - node degree statistics (min, max, mean, median) template <typename IterablePairs> void getGraphStatistics ( const int nb_nodes, const IterablePairs & pairs ) { const indexedGraph graph(pairs); if (lemon::countNodes(graph.g) > nb_nodes) return; // Compute node degree for each node std::vector<int> nodes_degree; for (indexedGraph::GraphT::NodeIt n(graph.g); n != lemon::INVALID; ++n) { nodes_degree.emplace_back(lemon::countOutArcs(graph.g, n)); } int min, max, mean, median; const bool stats = minMaxMeanMedian( nodes_degree.cbegin(), nodes_degree.cend(), min, max, mean, median); // Compute the number of connected component const auto connected_components = exportGraphToMapSubgraphs<indexedGraph::GraphT, IndexT>(graph.g); OPENMVG_LOG_INFO << "Graph statistics:\n" << "\t#nodes: " << nb_nodes<< "\n" << "\t#cc: " << connected_components.size() + (nb_nodes - lemon::countNodes(graph.g)) << "\n" << "\t#singleton: " << nb_nodes - lemon::countNodes(graph.g)<< "\n" << "\tNode degree statistics:\t" << "min: " << min << ", " << "max: " << max << ", " << "mean: " << mean << ", " << "median: " << median; } } } #endif // OPENMVG_GRAPH_GRAPH_STATS_HPP
1,895
C++
.h
54
32.333333
97
0.685104
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
27,150
sfm_preemptive_regions_provider.hpp
openMVG_openMVG/src/openMVG/sfm/pipelines/sfm_preemptive_regions_provider.hpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2019 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_SFM_PREEMPTIVE_REGIONS_PROVIDER_HPP #define OPENMVG_SFM_SFM_PREEMPTIVE_REGIONS_PROVIDER_HPP #include "openMVG/sfm/pipelines/sfm_regions_provider.hpp" namespace openMVG { namespace sfm { /// Abstract Regions provider /// Allow to load and return a subset of regions related to a view struct Preemptive_Regions_Provider : public Regions_Provider { public: /// Set the number of regions to keep per image (largest scale kept first) explicit Preemptive_Regions_Provider(int kept_regions_count = 100): Regions_Provider(), kept_regions_count_(kept_regions_count) {}; // Load Regions related to a provided SfM_Data View container bool load( const SfM_Data & sfm_data, const std::string & feat_directory, std::unique_ptr<features::Regions>& region_type, system::ProgressInterface * my_progress_bar = nullptr) override { if (!my_progress_bar) my_progress_bar = &system::ProgressInterface::dummy(); region_type_.reset(region_type->EmptyClone()); my_progress_bar->Restart(sfm_data.GetViews().size(), "- Regions ---- Loading -"); // Read for each view the corresponding regions and store them std::atomic<bool> bContinue(true); #ifdef OPENMVG_USE_OPENMP #pragma omp parallel #endif for (Views::const_iterator iter = sfm_data.GetViews().begin(); iter != sfm_data.GetViews().end() && bContinue; ++iter) { if (my_progress_bar->hasBeenCanceled()) { bContinue = false; continue; } #ifdef OPENMVG_USE_OPENMP #pragma omp single nowait #endif { const std::string sImageName = stlplus::create_filespec(sfm_data.s_root_path, iter->second->s_Img_path); const std::string basename = stlplus::basename_part(sImageName); const std::string featFile = stlplus::create_filespec(feat_directory, basename, ".feat"); const std::string descFile = stlplus::create_filespec(feat_directory, basename, ".desc"); std::unique_ptr<features::Regions> regions_ptr(region_type->EmptyClone()); if (!regions_ptr->Load(featFile, descFile)) { OPENMVG_LOG_ERROR << "Invalid regions files for the view: " << sImageName; bContinue = false; } //else #ifdef OPENMVG_USE_OPENMP #pragma omp critical #endif { // Sort regions by feature scale & keep the desired count regions_ptr->SortAndSelectByRegionScale(kept_regions_count_); cache_[iter->second->id_view] = std::move(regions_ptr); } ++(*my_progress_bar); } } return bContinue; } protected: int kept_regions_count_ = 100; }; // Preemptive_Regions_Provider } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_SFM_PREEMPTIVE_REGIONS_PROVIDER_HPP
3,106
C++
.h
77
35.246753
112
0.689987
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
27,170
SfmSceneInitializer.hpp
openMVG_openMVG/src/openMVG/sfm/pipelines/sequential/SfmSceneInitializer.hpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2018 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_SCENE_INITIALIZER_HPP #define OPENMVG_SFM_SCENE_INITIALIZER_HPP namespace openMVG { namespace sfm { struct SfM_Data; struct Features_Provider; struct Matches_Provider; // Interface to initialize a sfm_data with some camera poses. // It allows to generate a 3D seed for a sequential SfM pipeline. class SfMSceneInitializer { public: SfMSceneInitializer( SfM_Data & sfm_data, const Features_Provider * features_provider, const Matches_Provider * matches_provider) :sfm_data_(sfm_data), features_provider_(features_provider), matches_provider_(matches_provider) { }; virtual ~SfMSceneInitializer() = default; virtual bool Process() { return true; }; const SfM_Data & Get_sfm_data() const {return sfm_data_;}; protected: SfM_Data & sfm_data_; const Features_Provider * features_provider_; const Matches_Provider * matches_provider_; }; } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_SCENE_INITIALIZER_HPP
1,318
C++
.h
39
31.153846
76
0.750198
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
27,174
sfm_stellar_engine.hpp
openMVG_openMVG/src/openMVG/sfm/pipelines/stellar/sfm_stellar_engine.hpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2017 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_STELLAR_ENGINE_HPP #define OPENMVG_SFM_STELLAR_ENGINE_HPP #include <memory> #include <string> #include "openMVG/sfm/pipelines/global/GlobalSfM_rotation_averaging.hpp" #include "openMVG/sfm/pipelines/global/GlobalSfM_translation_averaging.hpp" #include "openMVG/sfm/pipelines/sfm_engine.hpp" namespace htmlDocument { class htmlDocumentStream; } namespace openMVG { namespace matching { struct PairWiseMatches; } } namespace openMVG { namespace sfm { struct Features_Provider; } } namespace openMVG { namespace sfm { struct Matches_Provider; } } namespace openMVG { namespace sfm { struct SfM_Data; } } namespace openMVG{ namespace sfm{ enum class EGraphSimplification : uint8_t { NONE, STAR_X, MST_X }; /// A Stellar SfM Pipeline Reconstruction Engine: /// - Use a local relative motion refinement, /// - Fuse groups or relative motions. class StellarSfMReconstructionEngine : public ReconstructionEngine { public: StellarSfMReconstructionEngine( const SfM_Data & sfm_data, const std::string & out_directory_logging, const std::string & logging_file = ""); ~StellarSfMReconstructionEngine() override; void SetFeaturesProvider(Features_Provider * provider); void SetMatchesProvider(Matches_Provider * provider); void SetGraphSimplification(const EGraphSimplification graph_simplification, const int value); bool Process() override; protected: /// Compute relative rotations & translations void ComputeRelativeMotions ( Hash_Map<Pair, geometry::Pose3> & relative_poses ) const; // Structure to store a stellar reconstruction // A series of relative motions centered in one pose Id struct StellarPodRelativeMotions { struct RelativeMotion { Mat3 rotation; Vec3 translation; }; Hash_Map<Pair, RelativeMotion> relative_motions; // relative motions in the stellar pod }; bool ComputeStellarReconstructions ( const Hash_Map<Pair, geometry::Pose3> & relative_poses, Hash_Map<IndexT, StellarPodRelativeMotions> & stellar_reconstruction_per_pose ) const; /// Compute the global rotations from the relative rotations bool Compute_Global_Rotations ( const openMVG::rotation_averaging::RelativeRotations & vec_relatives_R, Hash_Map<IndexT, Mat3> & map_globalR, Pair_Set & used_pairs ) const; /// Compute global translations bool Compute_Global_Translations ( const Hash_Map<IndexT, Mat3> & global_rotations, const Pair_Set & used_pairs, const Hash_Map<IndexT, StellarPodRelativeMotions> & stellar_reconstruction_per_pose ); bool Compute_Initial_Structure(const int min_covisibility = 2); bool Adjust(); private: // HTML logger std::shared_ptr<htmlDocument::htmlDocumentStream> html_doc_stream_; std::string logging_file_; //-- Data provider Features_Provider * features_provider_; Matches_Provider * matches_provider_; //-- Graph simplication for Stellar configurations EGraphSimplification graph_simplification_; int graph_simplification_value_; // Additional parameters (nb_tree or star satellite, ...) }; } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_STELLAR_ENGINE_HPP
3,495
C++
.h
91
35.428571
96
0.765385
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
27,195
cubic_image_sampler.hpp
openMVG_openMVG/src/openMVG/spherical/cubic_image_sampler.hpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2020 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/spherical/image_resampling.hpp" #include <array> namespace openMVG { namespace spherical { /// Compute a rectilinear camera focal from a given angular desired FoV double FocalFromPinholeHeight ( int h, double fov_radian = openMVG::D2R(45) // Camera FoV ) { return h / (2 * tan(fov_radian)); } const static std::array<openMVG::Mat3,6> GetCubicRotations() { using namespace openMVG; return { RotationAroundY(D2R(0)) , // front RotationAroundY(D2R(-90)), // right RotationAroundY(D2R(-180)), // behind RotationAroundY(D2R(-270)), // left RotationAroundX(D2R(-90)), // up RotationAroundX(D2R(+90)) // down }; } openMVG::cameras::Pinhole_Intrinsic ComputeCubicCameraIntrinsics ( const int cubic_image_size, const double fov = D2R(45) ) { const double focal = spherical::FocalFromPinholeHeight(cubic_image_size, fov); const double principal_point_xy = cubic_image_size / 2; return cameras::Pinhole_Intrinsic(cubic_image_size, cubic_image_size, focal, principal_point_xy, principal_point_xy); } template <typename ImageT, typename SamplerT> void SphericalToCubic ( const ImageT & equirectangular_image, const openMVG::cameras::Pinhole_Intrinsic & pinhole_camera, std::vector<ImageT> & cube_images, const SamplerT sampler = image::Sampler2d<image::SamplerLinear>() ) { const std::array<Mat3, 6> rot_matrix = GetCubicRotations(); const std::vector<Mat3> rot_matrix_vec(rot_matrix.cbegin(), rot_matrix.cend()); SphericalToPinholes( equirectangular_image, pinhole_camera, cube_images, rot_matrix_vec, sampler); } } // namespace spherical } // namespace openMVG
2,143
C++
.h
66
27.712121
81
0.683116
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
27,196
image_resampling.hpp
openMVG_openMVG/src/openMVG/spherical/image_resampling.hpp
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2020 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "openMVG/cameras/Camera_Pinhole.hpp" #include "openMVG/cameras/Camera_Spherical.hpp" #include "openMVG/image/sample.hpp" #include "openMVG/numeric/eigen_alias_definition.hpp" namespace openMVG { namespace spherical { // Backward rendering of a pinhole image for a given rotation in a panorama template <typename ImageT, typename SamplerT> ImageT SphericalToPinhole ( const ImageT & equirectangular_image, const openMVG::cameras::Pinhole_Intrinsic & pinhole_camera, const Mat3 & rot_matrix = Mat3::Identity(), const SamplerT sampler = image::Sampler2d<image::SamplerLinear>() ) { using namespace openMVG; using namespace openMVG::cameras; // // Initialize a camera model for each image domain // - the equirectangular panorama const Intrinsic_Spherical sphere_camera(equirectangular_image.Width() - 1, equirectangular_image.Height() - 1); // Perform backward/inverse rendering: // - For each destination pixel in the pinhole image, // compute where to pick the pixel in the panorama image. // This is done by using bearing vector computation const int renderer_image_size = pinhole_camera.h(); ImageT pinhole_image(renderer_image_size, renderer_image_size); const int image_width = pinhole_image.Width(); const int image_height = pinhole_image.Height(); // Use image coordinate in a matrix to use OpenMVG camera bearing vector vectorization Mat2X xy_coords(2, static_cast<int>(image_width * image_height)); for (int y = 0; y < image_height; ++y) for (int x = 0; x < image_width; ++x) xy_coords.col(x + image_width * y ) << x +.5 , y + .5; // Compute bearing vectors const Mat3X bearing_vectors = pinhole_camera(xy_coords); // Compute rotation bearings const Mat3X rotated_bearings = rot_matrix * bearing_vectors; // For every pinhole image pixels #pragma omp parallel for for (int it = 0; it < rotated_bearings.cols(); ++it) { // Project the bearing vector to the sphere const Vec2 sphere_proj = sphere_camera.project(rotated_bearings.col(it)); // and use the corresponding pixel location in the panorama const Vec2 xy = xy_coords.col(it); if (equirectangular_image.Contains(sphere_proj.y(), sphere_proj.x())) { pinhole_image(xy.y(), xy.x()) = sampler(equirectangular_image, sphere_proj.y(), sphere_proj.x()); } } return pinhole_image; } // Sample pinhole image from a panorama given some camera rotations template <typename ImageT, typename SamplerT> void SphericalToPinholes ( const ImageT & equirectangular_image, const openMVG::cameras::Pinhole_Intrinsic & pinhole_camera, std::vector<ImageT> & pinhole_images, const std::vector<Mat3> & rotations, const SamplerT sampler = image::Sampler2d<image::SamplerLinear>() ) { pinhole_images.resize(rotations.size()); // render each cube faces for (int i_rot = 0; i_rot < rotations.size(); ++i_rot) { pinhole_images[i_rot] = SphericalToPinhole( equirectangular_image, pinhole_camera, rotations[i_rot], sampler); } } } // namespace spherical } // namespace openMVG
3,453
C++
.h
86
36.627907
103
0.723017
openMVG/openMVG
5,671
1,671
273
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false