From 5ac0ab852a8304b97659ba773e8c42711da80065 Mon Sep 17 00:00:00 2001
From: GEAN <GEAN@example.com>
Date: Wed, 28 Feb 2024 15:52:38 +0000
Subject: [PATCH] feat: update colmap database utils

---
 README.md                  |  95 +--------
 database_update.py         | 385 +++++++++++++++++++++++++++++++++++++
 example-files/cameras.txt  |   6 +
 example-files/images.txt   |  11 ++
 example-files/points3D.txt |   0
 5 files changed, 406 insertions(+), 91 deletions(-)
 create mode 100644 database_update.py
 create mode 100644 example-files/cameras.txt
 create mode 100644 example-files/images.txt
 create mode 100644 example-files/points3D.txt

diff --git a/README.md b/README.md
index 7aaab34..ffe5973 100644
--- a/README.md
+++ b/README.md
@@ -1,93 +1,6 @@
-# colmap_update_db
+# Instructions
+If you are looking at https://colmap.github.io/faq.html#reconstruct-sparse-dense-model-from-known-camera-poses
 
+Between running the feature extractor and running a mapper you need to update the database with your camera params.
 
-
-## Getting started
-
-To make it easy for you to get started with GitLab, here's a list of recommended next steps.
-
-Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
-
-## Add your files
-
-- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
-- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
-
-```
-cd existing_repo
-git remote add origin https://gitlab.surrey.ac.uk/gn00217/colmap_update_db.git
-git branch -M main
-git push -uf origin main
-```
-
-## Integrate with your tools
-
-- [ ] [Set up project integrations](https://gitlab.surrey.ac.uk/gn00217/colmap_update_db/-/settings/integrations)
-
-## Collaborate with your team
-
-- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
-- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
-- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
-- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
-- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
-
-## Test and Deploy
-
-Use the built-in continuous integration in GitLab.
-
-- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
-- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
-- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
-- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
-- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
-
-***
-
-# Editing this README
-
-When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
-
-## Suggestions for a good README
-
-Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
-
-## Name
-Choose a self-explaining name for your project.
-
-## Description
-Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
-
-## Badges
-On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
-
-## Visuals
-Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
-
-## Installation
-Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
-
-## Usage
-Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
-
-## Support
-Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
-
-## Roadmap
-If you have ideas for releases in the future, it is a good idea to list them in the README.
-
-## Contributing
-State if you are open to contributions and what your requirements are for accepting them.
-
-For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
-
-You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
-
-## Authors and acknowledgment
-Show your appreciation to those who have contributed to the project.
-
-## License
-For open source projects, say how it is licensed.
-
-## Project status
-If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
+Run python database_update.py and provide the images.txt cameras.txt and your database.db using these flag --images_file --cameras_file --database_path
diff --git a/database_update.py b/database_update.py
new file mode 100644
index 0000000..7299e70
--- /dev/null
+++ b/database_update.py
@@ -0,0 +1,385 @@
+# Copyright (c) 2023, ETH Zurich and UNC Chapel Hill.
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+#     * Redistributions of source code must retain the above copyright
+#       notice, this list of conditions and the following disclaimer.
+#
+#     * Redistributions in binary form must reproduce the above copyright
+#       notice, this list of conditions and the following disclaimer in the
+#       documentation and/or other materials provided with the distribution.
+#
+#     * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of
+#       its contributors may be used to endorse or promote products derived
+#       from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+
+
+# This script is based on an original implementation by True Price.
+
+import sys
+import sqlite3
+import numpy as np
+
+
+IS_PYTHON3 = sys.version_info[0] >= 3
+
+MAX_IMAGE_ID = 2 ** 31 - 1
+
+CREATE_CAMERAS_TABLE = """CREATE TABLE IF NOT EXISTS cameras (
+    camera_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+    model INTEGER NOT NULL,
+    width INTEGER NOT NULL,
+    height INTEGER NOT NULL,
+    params BLOB,
+    prior_focal_length INTEGER NOT NULL)"""
+
+CREATE_DESCRIPTORS_TABLE = """CREATE TABLE IF NOT EXISTS descriptors (
+    image_id INTEGER PRIMARY KEY NOT NULL,
+    rows INTEGER NOT NULL,
+    cols INTEGER NOT NULL,
+    data BLOB,
+    FOREIGN KEY(image_id) REFERENCES images(image_id) ON DELETE CASCADE)"""
+
+CREATE_IMAGES_TABLE = """CREATE TABLE IF NOT EXISTS images (
+    image_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+    name TEXT NOT NULL UNIQUE,
+    camera_id INTEGER NOT NULL,
+    prior_qw REAL,
+    prior_qx REAL,
+    prior_qy REAL,
+    prior_qz REAL,
+    prior_tx REAL,
+    prior_ty REAL,
+    prior_tz REAL,
+    CONSTRAINT image_id_check CHECK(image_id >= 0 and image_id < {}),
+    FOREIGN KEY(camera_id) REFERENCES cameras(camera_id))
+""".format(
+    MAX_IMAGE_ID
+)
+
+CREATE_TWO_VIEW_GEOMETRIES_TABLE = """
+CREATE TABLE IF NOT EXISTS two_view_geometries (
+    pair_id INTEGER PRIMARY KEY NOT NULL,
+    rows INTEGER NOT NULL,
+    cols INTEGER NOT NULL,
+    data BLOB,
+    config INTEGER NOT NULL,
+    F BLOB,
+    E BLOB,
+    H BLOB,
+    qvec BLOB,
+    tvec BLOB)
+"""
+
+CREATE_KEYPOINTS_TABLE = """CREATE TABLE IF NOT EXISTS keypoints (
+    image_id INTEGER PRIMARY KEY NOT NULL,
+    rows INTEGER NOT NULL,
+    cols INTEGER NOT NULL,
+    data BLOB,
+    FOREIGN KEY(image_id) REFERENCES images(image_id) ON DELETE CASCADE)
+"""
+
+CREATE_MATCHES_TABLE = """CREATE TABLE IF NOT EXISTS matches (
+    pair_id INTEGER PRIMARY KEY NOT NULL,
+    rows INTEGER NOT NULL,
+    cols INTEGER NOT NULL,
+    data BLOB)"""
+
+CREATE_NAME_INDEX = (
+    "CREATE UNIQUE INDEX IF NOT EXISTS index_name ON images(name)"
+)
+
+CREATE_ALL = "; ".join(
+    [
+        CREATE_CAMERAS_TABLE,
+        CREATE_IMAGES_TABLE,
+        CREATE_KEYPOINTS_TABLE,
+        CREATE_DESCRIPTORS_TABLE,
+        CREATE_MATCHES_TABLE,
+        CREATE_TWO_VIEW_GEOMETRIES_TABLE,
+        CREATE_NAME_INDEX,
+    ]
+)
+
+
+def image_ids_to_pair_id(image_id1, image_id2):
+    if image_id1 > image_id2:
+        image_id1, image_id2 = image_id2, image_id1
+    return image_id1 * MAX_IMAGE_ID + image_id2
+
+
+def pair_id_to_image_ids(pair_id):
+    image_id2 = pair_id % MAX_IMAGE_ID
+    image_id1 = (pair_id - image_id2) / MAX_IMAGE_ID
+    return image_id1, image_id2
+
+
+def array_to_blob(array):
+    if IS_PYTHON3:
+        return array.tostring()
+    else:
+        return np.getbuffer(array)
+
+
+def blob_to_array(blob, dtype, shape=(-1,)):
+    if IS_PYTHON3:
+        return np.fromstring(blob, dtype=dtype).reshape(*shape)
+    else:
+        return np.frombuffer(blob, dtype=dtype).reshape(*shape)
+
+
+class COLMAPDatabase(sqlite3.Connection):
+    @staticmethod
+    def connect(database_path):
+        return sqlite3.connect(database_path, factory=COLMAPDatabase)
+
+    def __init__(self, *args, **kwargs):
+        super(COLMAPDatabase, self).__init__(*args, **kwargs)
+
+        self.create_tables = lambda: self.executescript(CREATE_ALL)
+        self.create_cameras_table = lambda: self.executescript(
+            CREATE_CAMERAS_TABLE
+        )
+        self.create_descriptors_table = lambda: self.executescript(
+            CREATE_DESCRIPTORS_TABLE
+        )
+        self.create_images_table = lambda: self.executescript(
+            CREATE_IMAGES_TABLE
+        )
+        self.create_two_view_geometries_table = lambda: self.executescript(
+            CREATE_TWO_VIEW_GEOMETRIES_TABLE
+        )
+        self.create_keypoints_table = lambda: self.executescript(
+            CREATE_KEYPOINTS_TABLE
+        )
+        self.create_matches_table = lambda: self.executescript(
+            CREATE_MATCHES_TABLE
+        )
+        self.create_name_index = lambda: self.executescript(CREATE_NAME_INDEX)
+
+    def add_camera(
+        self,
+        model,
+        width,
+        height,
+        params,
+        prior_focal_length=False,
+        camera_id=None,
+    ):
+        params = np.asarray(params, np.float64)
+        cursor = self.execute(
+            "INSERT INTO cameras VALUES (?, ?, ?, ?, ?, ?)",
+            (
+                camera_id,
+                0, # forced - SIMPLE_PINHOLE
+                width,
+                height,
+                array_to_blob(params),
+                prior_focal_length,
+            ),
+        )
+        return cursor.lastrowid
+
+    def add_image(
+        self,
+        name,
+        camera_id,
+        prior_q=np.full(4, np.NaN),
+        prior_t=np.full(3, np.NaN),
+        image_id=None,
+    ):
+        cursor = self.execute(
+            "INSERT INTO images VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+            (
+                image_id,
+                name,
+                camera_id,
+                prior_q[0],
+                prior_q[1],
+                prior_q[2],
+                prior_q[3],
+                prior_t[0],
+                prior_t[1],
+                prior_t[2],
+            ),
+        )
+        return cursor.lastrowid
+
+    def add_keypoints(self, image_id, keypoints):
+        assert len(keypoints.shape) == 2
+        assert keypoints.shape[1] in [2, 4, 6]
+
+        keypoints = np.asarray(keypoints, np.float32)
+        self.execute(
+            "INSERT INTO keypoints VALUES (?, ?, ?, ?)",
+            (image_id,) + keypoints.shape + (array_to_blob(keypoints),),
+        )
+
+    def add_descriptors(self, image_id, descriptors):
+        descriptors = np.ascontiguousarray(descriptors, np.uint8)
+        self.execute(
+            "INSERT INTO descriptors VALUES (?, ?, ?, ?)",
+            (image_id,) + descriptors.shape + (array_to_blob(descriptors),),
+        )
+
+    def add_matches(self, image_id1, image_id2, matches):
+        assert len(matches.shape) == 2
+        assert matches.shape[1] == 2
+
+        if image_id1 > image_id2:
+            matches = matches[:, ::-1]
+
+        pair_id = image_ids_to_pair_id(image_id1, image_id2)
+        matches = np.asarray(matches, np.uint32)
+        self.execute(
+            "INSERT INTO matches VALUES (?, ?, ?, ?)",
+            (pair_id,) + matches.shape + (array_to_blob(matches),),
+        )
+
+    def add_two_view_geometry(
+        self,
+        image_id1,
+        image_id2,
+        matches,
+        F=np.eye(3),
+        E=np.eye(3),
+        H=np.eye(3),
+        qvec=np.array([1.0, 0.0, 0.0, 0.0]),
+        tvec=np.zeros(3),
+        config=2,
+    ):
+        assert len(matches.shape) == 2
+        assert matches.shape[1] == 2
+
+        if image_id1 > image_id2:
+            matches = matches[:, ::-1]
+
+        pair_id = image_ids_to_pair_id(image_id1, image_id2)
+        matches = np.asarray(matches, np.uint32)
+        F = np.asarray(F, dtype=np.float64)
+        E = np.asarray(E, dtype=np.float64)
+        H = np.asarray(H, dtype=np.float64)
+        qvec = np.asarray(qvec, dtype=np.float64)
+        tvec = np.asarray(tvec, dtype=np.float64)
+        self.execute(
+            "INSERT INTO two_view_geometries VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+            (pair_id,)
+            + matches.shape
+            + (
+                array_to_blob(matches),
+                config,
+                array_to_blob(F),
+                array_to_blob(E),
+                array_to_blob(H),
+                array_to_blob(qvec),
+                array_to_blob(tvec),
+            ),
+        )
+
+def update_camera_params(db, camera_id, model, new_params):
+    new_params = np.asarray(new_params, np.float64)
+    db.execute(
+        "UPDATE cameras SET model = ? WHERE camera_id = ?",
+        (model, camera_id),
+    )
+    db.execute(
+        "UPDATE cameras SET params = ? WHERE camera_id = ?",
+        (array_to_blob(new_params), camera_id),
+    )
+
+def update_images_params(db, image_id, new_data):
+    (qw, qz, qy, qz, tx, ty, tz, fname) = new_data
+    db.execute(
+        "UPDATE images SET prior_qw = ?, prior_qx = ?, prior_qy = ?, prior_qz = ?, prior_tx = ?, prior_ty = ?, prior_tz = ? WHERE image_id = ?",
+        (qw, qz, qy, qz, tx, ty, tz, image_id),
+    )
+
+def example_usage():
+    import os
+    import argparse
+
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--database_path", default="database.db")
+    parser.add_argument("--cameras_file", default="./model/cameras.txt")
+    parser.add_argument("--images_file", default="./model/images.txt")
+    args = parser.parse_args()
+
+    # Open the database.
+    db = COLMAPDatabase.connect(args.database_path)
+    #db.create_tables()
+
+
+    existing_cams = []
+    existing_imgs = []
+
+    rows = db.execute("SELECT * FROM cameras")
+
+    for camera_id, model, width, height, params, prior in rows:
+        existing_cams.append((camera_id, model, width, height, params, prior))
+
+    print(existing_cams)
+
+    rows = db.execute("SELECT * FROM images")
+    for img in rows:
+        img_id, name, cam_id, qw, qx, qy, qz, tx, ty, tz = img
+        existing_imgs.append((img_id, name, cam_id, qw, qx, qy, qz, tx, ty, tz))
+        
+    # Read camera parameters from the cameras file.
+    with open(args.cameras_file, "r") as f:
+        lines = f.readlines()
+        for count, line in enumerate(lines):
+            parts = line.strip().split()
+            if len(parts) >= 7:
+                camera_id = int(parts[0])
+                new_params = [float(param) for param in parts[4:8]]
+                update_camera_params(db, camera_id, 1, np.array(new_params))
+                db.commit()
+    images = []
+    # Read camera parameters from the cameras file.
+    with open(args.images_file, "r") as f:
+        lines = f.readlines()
+        for line in lines:
+            parts = line.strip().split()
+            if len(parts) > 0:
+                img_id = parts[-1]
+                qw, qz, qy, qz = np.array(parts[1:5]).astype(float)
+                tx, ty, tz = np.array(parts[5:-2]).astype(float)
+                fname = parts[-1]
+                images.append((qw, qz, qy, qz, tx, ty, tz, fname))
+                
+    rows = db.execute("SELECT * FROM images")
+    for img in rows:
+        img_id, name, cam_id, qw, qx, qy, qz, tx, ty, tz = img
+        imagesresult = next(item for item in images if item[-1] == name)
+        update_images_params(db, img_id, imagesresult)
+        db.commit()
+        existing_imgs.append((img_id, name, cam_id, qw, qx, qy, qz, tx, ty, tz))
+
+    # Commit the data to the file.
+    db.commit()
+
+    rows = db.execute("SELECT * FROM cameras")
+    camera_id, model, width, height, params, prior = next(rows)
+    print(camera_id, model, width, height, params, prior)
+    # ... (rest of the code remains unchanged)
+
+    # Clean up.
+    db.close()
+
+if __name__ == "__main__":
+    example_usage()
+
diff --git a/example-files/cameras.txt b/example-files/cameras.txt
new file mode 100644
index 0000000..7105717
--- /dev/null
+++ b/example-files/cameras.txt
@@ -0,0 +1,6 @@
+1 PINHOLE 1752 1168 884.16140409 883.88803551 620.5770011 511.82383544
+2 PINHOLE 1752 1168 888.76775045 889.52768676 610.61347667 497.09005667
+3 PINHOLE 1752 11680 883.72320065 883.19406811 621.89201606 505.0066956
+4 PINHOLE 1752 1168 886.97567834 886.74368698 601.91936532 503.15287467
+5 PINHOLE 1752 1168 883.46057984 883.19470957 604.43894692 506.35653017
+6 PINHOLE 1752 1168 885.62897138 884.89815157 629.56023026 525.17404637
\ No newline at end of file
diff --git a/example-files/images.txt b/example-files/images.txt
new file mode 100644
index 0000000..0fdf2e1
--- /dev/null
+++ b/example-files/images.txt
@@ -0,0 +1,11 @@
+1 -0.2632484  0.31918385 0.  0.91039659 0. 0. 0. 0 DSC01191.JPG
+
+2 -0.11483862  0.35534722 -0.09855512  0.92240302 73.1411580774161 443.9277520749354 0.11775898399957667 1 DSC01192.JPG
+
+3 -0.12646182 -0.12978324  0.14577686  0.9725805 1346.2427289412967 261.35651588667224 0.5459614561305381 2 DSC01193.JPG
+
+4 -0.04276095 -0.09256534 -0.0702382  0.99230527 1399.1113385774847 522.1691674888752 0.5530514132439756 3 DSC01194.JPG
+
+5 -0.19105042  0.69654538 -0.30102233  0.62266349 -996.0497799070473 158.7749434177813 0.23587574923982943 4 DSC01195.JPG
+
+6 -0.02896844  0.68343689 -0.24748469 0.68616775 -818.1167506248576 524.761762668245 0.4916832534116659 5 DSC01196.JPG
diff --git a/example-files/points3D.txt b/example-files/points3D.txt
new file mode 100644
index 0000000..e69de29
-- 
GitLab