CoolFace
Modelpublic

beverley-gorry/colmap-vslamlab

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
export_to_bundler.py179 linesDownload Raw Back to python
1# Copyright (c), ETH Zurich and UNC Chapel Hill.2# All rights reserved.3#4# Redistribution and use in source and binary forms, with or without5# modification, are permitted provided that the following conditions are met:6#7#     * Redistributions of source code must retain the above copyright8#       notice, this list of conditions and the following disclaimer.9#10#     * Redistributions in binary form must reproduce the above copyright11#       notice, this list of conditions and the following disclaimer in the12#       documentation and/or other materials provided with the distribution.13#14#     * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of15#       its contributors may be used to endorse or promote products derived16#       from this software without specific prior written permission.17#18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"19# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE21# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE22# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR23# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF24# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS25# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN26# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)27# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE28# POSSIBILITY OF SUCH DAMAGE.29 30 31# This script exports a COLMAP database to the file structure to run Bundler.32 33import argparse34import gzip35import os36import shutil37import sqlite338 39import numpy as np40 41 42def parse_args():43    parser = argparse.ArgumentParser()44    parser.add_argument("--database_path", required=True)45    parser.add_argument("--image_path", required=True)46    parser.add_argument("--output_path", required=True)47    parser.add_argument("--min_num_matches", type=int, default=15)48    args = parser.parse_args()49    return args50 51 52def pair_id_to_image_ids(pair_id):53    image_id2 = pair_id % 214748364754    image_id1 = (pair_id - image_id2) / 214748364755    return image_id1, image_id256 57 58def main():59    args = parse_args()60 61    connection = sqlite3.connect(args.database_path)62    cursor = connection.cursor()63 64    try:65        os.makedirs(args.output_path)66    except:  # noqa E72267        pass68 69    cameras = {}70    cursor.execute("SELECT camera_id, params FROM cameras;")71    for row in cursor:72        camera_id = row[0]73        params = np.fromstring(row[1], dtype=np.double)74        cameras[camera_id] = params75 76    images = {}77    with open(os.path.join(args.output_path, "list.txt"), "w") as fid:78        cursor.execute("SELECT image_id, camera_id, name FROM images;")79        for row in cursor:80            image_id = row[0]81            camera_id = row[1]82            image_name = row[2]83            print("Copying image", image_name)84            images[image_id] = (len(images), image_name)85            fid.write("./%s 0 %f\n" % (image_name, cameras[camera_id][0]))86            if not os.path.exists(os.path.join(args.output_path, image_name)):87                shutil.copyfile(88                    os.path.join(args.image_path, image_name),89                    os.path.join(args.output_path, image_name),90                )91 92    for image_id, (image_idx, image_name) in images.iteritems():93        print("Exporting key file for", image_name)94        base_name, ext = os.path.splitext(image_name)95        key_file_name = os.path.join(args.output_path, base_name + ".key")96        key_file_name_gz = key_file_name + ".gz"97        if os.path.exists(key_file_name_gz):98            continue99 100        cursor.execute(101            "SELECT data FROM keypoints WHERE image_id=?;", (image_id,)102        )103        row = next(cursor)104        if row[0] is None:105            keypoints = np.zeros((0, 6), dtype=np.float32)106            descriptors = np.zeros((0, 128), dtype=np.uint8)107        else:108            keypoints = np.fromstring(row[0], dtype=np.float32).reshape(-1, 6)109            cursor.execute(110                "SELECT data FROM descriptors WHERE image_id=?;", (image_id,)111            )112            row = next(cursor)113            descriptors = np.fromstring(row[0], dtype=np.uint8).reshape(-1, 128)114 115        with open(key_file_name, "w") as fid:116            fid.write("%d %d\n" % (keypoints.shape[0], descriptors.shape[1]))117            for r in range(keypoints.shape[0]):118                fid.write(119                    "%f %f %f %f\n"120                    % (121                        keypoints[r, 1],122                        keypoints[r, 0],123                        keypoints[r, 2],124                        keypoints[r, 3],125                    )126                )127                for i in range(0, 128, 20):128                    desc_block = descriptors[r, i : i + 20]129                    fid.write(" ".join(map(str, desc_block.ravel().tolist())))130                    fid.write("\n")131 132        with open(key_file_name, "rb") as fid_in:133            with gzip.open(key_file_name + ".gz", "wb") as fid_out:134                fid_out.writelines(fid_in)135 136        os.remove(key_file_name)137 138    with open(os.path.join(args.output_path, "matches.init.txt"), "w") as fid:139        cursor.execute(140            "SELECT pair_id, data FROM two_view_geometries WHERE rows>=?;",141            (args.min_num_matches,),142        )143        for row in cursor:144            pair_id = row[0]145            inlier_matches = np.fromstring(row[1], dtype=np.uint32).reshape(146                -1, 2147            )148            image_id1, image_id2 = pair_id_to_image_ids(pair_id)149            image_idx1 = images[image_id1][0]150            image_idx2 = images[image_id2][0]151            fid.write(152                "%d %d\n%d\n"153                % (image_idx1, image_idx2, inlier_matches.shape[0])154            )155            for i in range(inlier_matches.shape[0]):156                fid.write(157                    "%d %d\n" % (inlier_matches[i, 0], inlier_matches[i, 1])158                )159 160    with open(os.path.join(args.output_path, "run_bundler.sh"), "w") as fid:161        fid.write("bin/Bundler list.txt \\\n")162        fid.write("--run_bundle \\\n")163        fid.write("--use_focal_estimate \\\n")164        fid.write("--output_all bundle_ \\\n")165        fid.write("--constrain_focal \\\n")166        fid.write("--estimate_distortion \\\n")167        fid.write("--match_table matches.init.txt \\\n")168        fid.write("--variable_focal_length \\\n")169        fid.write("--output_dir bundle \\\n")170        fid.write("--output bundle.out \\\n")171        fid.write("--constrain_focal_weight 0.0001 \\\n")172 173    cursor.close()174    connection.close()175 176 177if __name__ == "__main__":178    main()179