beverley-gorry/colmap-vslamlab
0
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 VisualSfM.32 33import argparse34import os35import shutil36import sqlite337import struct38 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 parser.add_argument("--binary_feature_files", type=bool, default=True)49 args = parser.parse_args()50 return args51 52 53def pair_id_to_image_ids(pair_id):54 image_id2 = pair_id % 214748364755 image_id1 = (pair_id - image_id2) / 214748364756 return image_id1, image_id257 58 59def main():60 args = parse_args()61 62 connection = sqlite3.connect(args.database_path)63 cursor = connection.cursor()64 65 try:66 os.makedirs(args.output_path)67 except: # noqa E72268 pass69 70 cameras = {}71 cursor.execute("SELECT camera_id, params FROM cameras;")72 for row in cursor:73 camera_id = row[0]74 params = np.fromstring(row[1], dtype=np.double)75 cameras[camera_id] = params76 77 images = {}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 if not os.path.exists(os.path.join(args.output_path, image_name)):86 shutil.copyfile(87 os.path.join(args.image_path, image_name),88 os.path.join(args.output_path, image_name),89 )90 91 # The magic numbers used in VisualSfM's binary file format for storing the92 # feature descriptors.93 sift_name = 141389243594 sift_version_v4 = 80833442295 sift_eof_marker = 117960038396 97 for image_id, (image_idx, image_name) in images.iteritems():98 print("Exporting key file for", image_name)99 base_name, ext = os.path.splitext(image_name)100 key_file_name = os.path.join(args.output_path, base_name + ".sift")101 if os.path.exists(key_file_name):102 continue103 104 cursor.execute(105 "SELECT data FROM keypoints WHERE image_id=?;", (image_id,)106 )107 row = next(cursor)108 if row[0] is None:109 keypoints = np.zeros((0, 6), dtype=np.float32)110 descriptors = np.zeros((0, 128), dtype=np.uint8)111 else:112 keypoints = np.fromstring(row[0], dtype=np.float32).reshape(-1, 6)113 cursor.execute(114 "SELECT data FROM descriptors WHERE image_id=?;", (image_id,)115 )116 row = next(cursor)117 descriptors = np.fromstring(row[0], dtype=np.uint8).reshape(-1, 128)118 119 if args.binary_feature_files:120 with open(key_file_name, "wb") as fid:121 fid.write(struct.pack("i", sift_name))122 fid.write(struct.pack("i", sift_version_v4))123 fid.write(struct.pack("i", keypoints.shape[0]))124 fid.write(struct.pack("i", 4))125 fid.write(struct.pack("i", 128))126 keypoints[:, :4].astype(np.float32).tofile(fid)127 descriptors.astype(np.uint8).tofile(fid)128 fid.write(struct.pack("i", sift_eof_marker))129 else:130 with open(key_file_name, "w") as fid:131 fid.write(132 "%d %d\n" % (keypoints.shape[0], descriptors.shape[1])133 )134 for r in range(keypoints.shape[0]):135 fid.write("%f %f 0 0 " % (keypoints[r, 0], keypoints[r, 1]))136 fid.write(137 " ".join(map(str, descriptors[r].ravel().tolist()))138 )139 fid.write("\n")140 141 with open(os.path.join(args.output_path, "matches.txt"), "w") as fid:142 cursor.execute(143 "SELECT pair_id, data FROM two_view_geometries WHERE rows>=?;",144 (args.min_num_matches,),145 )146 for row in cursor:147 pair_id = row[0]148 inlier_matches = np.fromstring(row[1], dtype=np.uint32).reshape(149 -1, 2150 )151 image_id1, image_id2 = pair_id_to_image_ids(pair_id)152 image_name1 = images[image_id1][1]153 image_name2 = images[image_id2][1]154 fid.write(155 "%s %s %d\n"156 % (image_name1, image_name2, inlier_matches.shape[0])157 )158 line1 = ""159 line2 = ""160 for i in range(inlier_matches.shape[0]):161 line1 += "%d " % inlier_matches[i, 0]162 line2 += "%d " % inlier_matches[i, 1]163 fid.write(line1 + "\n")164 fid.write(line2 + "\n")165 166 cursor.close()167 connection.close()168 169 170if __name__ == "__main__":171 main()172 