Skip to content

Commit

Permalink
style: reformat code for improved readability and line length consist…
Browse files Browse the repository at this point in the history
…ency
  • Loading branch information
yxlao committed Dec 28, 2024
1 parent 25f5db3 commit a81124a
Show file tree
Hide file tree
Showing 20 changed files with 340 additions and 114 deletions.
20 changes: 15 additions & 5 deletions camtools/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ def create_camera_frustums(
image_whs: Optional[List[List[int]]] = None,
size: float = 0.1,
color: Tuple[float, float, float] = (0, 0, 1),
highlight_color_map: Optional[Dict[int, Tuple[float, float, float]]] = None,
highlight_color_map: Optional[
Dict[int, Tuple[float, float, float]]
] = None,
center_line: bool = True,
center_line_color: Tuple[float, float, float] = (1, 0, 0),
up_triangle: bool = True,
Expand Down Expand Up @@ -72,7 +74,9 @@ def create_camera_frustums(
if not isinstance(w, (int, np.integer)) or not isinstance(
h, (int, np.integer)
):
raise ValueError(f"image_wh must be integer, but got {image_wh}.")
raise ValueError(
f"image_wh must be integer, but got {image_wh}."
)

# Wrap the highlight_color_map dimensions.
if highlight_color_map is not None:
Expand Down Expand Up @@ -115,7 +119,9 @@ def create_camera_frustum_with_Ts(
image_whs: Optional[List[List[int]]] = None,
size: float = 0.1,
color: Tuple[float, float, float] = (0, 0, 1),
highlight_color_map: Optional[Dict[int, Tuple[float, float, float]]] = None,
highlight_color_map: Optional[
Dict[int, Tuple[float, float, float]]
] = None,
center_line: bool = True,
center_line_color: Tuple[float, float, float] = (1, 0, 0),
up_triangle: bool = True,
Expand Down Expand Up @@ -209,7 +215,9 @@ def _create_camera_frustum(
sanity.assert_shape_3(color, "color")

w, h = image_wh
if not isinstance(w, (int, np.integer)) or not isinstance(h, (int, np.integer)):
if not isinstance(w, (int, np.integer)) or not isinstance(
h, (int, np.integer)
):
raise ValueError(f"image_wh must be integer, but got {image_wh}.")

R, _ = convert.T_to_R_t(T)
Expand All @@ -223,7 +231,9 @@ def _create_camera_frustum(
[0, h - 1, 1],
]
)
camera_plane_points_3d = (np.linalg.inv(K) @ camera_plane_points_2d_homo.T).T
camera_plane_points_3d = (
np.linalg.inv(K) @ camera_plane_points_2d_homo.T
).T
camera_plane_dist = solver.point_plane_distance_three_points(
[0, 0, 0], camera_plane_points_3d
)
Expand Down
57 changes: 42 additions & 15 deletions camtools/colmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,9 @@ def qvec2rotmat(self):
)


def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"):
def read_next_bytes(
fid, num_bytes, format_char_sequence, endian_character="<"
):
"""Read and unpack the next bytes from a binary file.
:param fid:
:param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.
Expand Down Expand Up @@ -158,7 +160,11 @@ def read_cameras_text(path):
height = int(elems[3])
params = np.array(tuple(map(float, elems[4:])))
cameras[camera_id] = Camera(
id=camera_id, model=model, width=width, height=height, params=params
id=camera_id,
model=model,
width=width,
height=height,
params=params,
)
return cameras

Expand All @@ -183,7 +189,9 @@ def read_cameras_binary(path_to_model_file):
height = camera_properties[3]
num_params = CAMERA_MODEL_IDS[model_id].num_params
params = read_next_bytes(
fid, num_bytes=8 * num_params, format_char_sequence="d" * num_params
fid,
num_bytes=8 * num_params,
format_char_sequence="d" * num_params,
)
cameras[camera_id] = Camera(
id=camera_id,
Expand Down Expand Up @@ -254,7 +262,10 @@ def read_images_text(path):
image_name = elems[9]
elems = fid.readline().split()
xys = np.column_stack(
[tuple(map(float, elems[0::3])), tuple(map(float, elems[1::3]))]
[
tuple(map(float, elems[0::3])),
tuple(map(float, elems[1::3])),
]
)
point3D_ids = np.array(tuple(map(int, elems[2::3])))
images[image_id] = Image(
Expand Down Expand Up @@ -291,16 +302,19 @@ def read_images_binary(path_to_model_file):
while current_char != b"\x00": # look for the ASCII 0 entry
image_name += current_char.decode("utf-8")
current_char = read_next_bytes(fid, 1, "c")[0]
num_points2D = read_next_bytes(fid, num_bytes=8, format_char_sequence="Q")[
0
]
num_points2D = read_next_bytes(
fid, num_bytes=8, format_char_sequence="Q"
)[0]
x_y_id_s = read_next_bytes(
fid,
num_bytes=24 * num_points2D,
format_char_sequence="ddq" * num_points2D,
)
xys = np.column_stack(
[tuple(map(float, x_y_id_s[0::3])), tuple(map(float, x_y_id_s[1::3]))]
[
tuple(map(float, x_y_id_s[0::3])),
tuple(map(float, x_y_id_s[1::3])),
]
)
point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))
images[image_id] = Image(
Expand Down Expand Up @@ -339,7 +353,13 @@ def write_images_text(images, path):
with open(path, "w") as fid:
fid.write(HEADER)
for _, img in images.items():
image_header = [img.id, *img.qvec, *img.tvec, img.camera_id, img.name]
image_header = [
img.id,
*img.qvec,
*img.tvec,
img.camera_id,
img.name,
]
first_line = " ".join(map(str, image_header))
fid.write(first_line + "\n")

Expand Down Expand Up @@ -419,9 +439,9 @@ def read_points3D_binary(path_to_model_file):
xyz = np.array(binary_point_line_properties[1:4])
rgb = np.array(binary_point_line_properties[4:7])
error = np.array(binary_point_line_properties[7])
track_length = read_next_bytes(fid, num_bytes=8, format_char_sequence="Q")[
0
]
track_length = read_next_bytes(
fid, num_bytes=8, format_char_sequence="Q"
)[0]
track_elems = read_next_bytes(
fid,
num_bytes=8 * track_length,
Expand Down Expand Up @@ -643,7 +663,8 @@ def quat_from_rotm(R):
q3[:, 3] = z
q = q0 * (w[:, None] > 0) + (w[:, None] == 0) * (
q1 * (x[:, None] > 0)
+ (x[:, None] == 0) * (q2 * (y[:, None] > 0) + (y[:, None] == 0) * (q3))
+ (x[:, None] == 0)
* (q2 * (y[:, None] > 0) + (y[:, None] == 0) * (q3))
)
q /= np.linalg.norm(q, axis=1, keepdims=True)
return q.squeeze()
Expand Down Expand Up @@ -819,15 +840,21 @@ def main():
)
args = parser.parse_args()

cameras, images, points3D = read_model(path=args.input_model, ext=args.input_format)
cameras, images, points3D = read_model(
path=args.input_model, ext=args.input_format
)

print("num_cameras:", len(cameras))
print("num_images:", len(images))
print("num_points3D:", len(points3D))

if args.output_model is not None:
write_model(
cameras, images, points3D, path=args.output_model, ext=args.output_format
cameras,
images,
points3D,
path=args.output_model,
ext=args.output_format,
)


Expand Down
44 changes: 33 additions & 11 deletions camtools/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ def pad_0001(array):
"""
if array.ndim == 2:
if not array.shape == (3, 4):
raise ValueError(f"Expected array of shape (3, 4), but got {array.shape}.")
raise ValueError(
f"Expected array of shape (3, 4), but got {array.shape}."
)
elif array.ndim == 3:
if not array.shape[-2:] == (3, 4):
raise ValueError(
Expand Down Expand Up @@ -56,7 +58,9 @@ def rm_pad_0001(array, check_vals=False):
# Check shapes.
if array.ndim == 2:
if not array.shape == (4, 4):
raise ValueError(f"Expected array of shape (4, 4), but got {array.shape}.")
raise ValueError(
f"Expected array of shape (4, 4), but got {array.shape}."
)
elif array.ndim == 3:
if not array.shape[-2:] == (4, 4):
raise ValueError(
Expand All @@ -77,7 +81,9 @@ def rm_pad_0001(array, check_vals=False):
)
elif array.ndim == 3:
bottom = array[:, 3:4, :]
expected_bottom = np.broadcast_to([0, 0, 0, 1], (array.shape[0], 1, 4))
expected_bottom = np.broadcast_to(
[0, 0, 0, 1], (array.shape[0], 1, 4)
)
if not np.allclose(bottom, expected_bottom):
raise ValueError(
f"Expected bottom row to be {expected_bottom}, but got {bottom}."
Expand All @@ -99,7 +105,9 @@ def to_homo(array):
A numpy array of shape (N, M+1) with a column of ones appended.
"""
if not isinstance(array, np.ndarray) or array.ndim != 2:
raise ValueError(f"Input must be a 2D numpy array, but got {array.shape}.")
raise ValueError(
f"Input must be a 2D numpy array, but got {array.shape}."
)

ones = np.ones((array.shape[0], 1), dtype=array.dtype)
return np.hstack((array, ones))
Expand All @@ -117,7 +125,9 @@ def from_homo(array):
A numpy array of shape (N, M-1) in Cartesian coordinates.
"""
if not isinstance(array, np.ndarray) or array.ndim != 2:
raise ValueError(f"Input must be a 2D numpy array, but got {array.shape}.")
raise ValueError(
f"Input must be a 2D numpy array, but got {array.shape}."
)
if array.shape[1] < 2:
raise ValueError(
f"Input array must have at least two columns for removing "
Expand Down Expand Up @@ -211,7 +221,9 @@ def pose_to_T(pose):
return np.linalg.inv(pose)


def T_opengl_to_opencv(T: Float[np.ndarray, "4 4"]) -> Float[np.ndarray, "4 4"]:
def T_opengl_to_opencv(
T: Float[np.ndarray, "4 4"]
) -> Float[np.ndarray, "4 4"]:
"""
Convert T from OpenGL convention to OpenCV convention.
Expand Down Expand Up @@ -239,7 +251,9 @@ def T_opengl_to_opencv(T: Float[np.ndarray, "4 4"]) -> Float[np.ndarray, "4 4"]:
return T


def T_opencv_to_opengl(T: Float[np.ndarray, "4 4"]) -> Float[np.ndarray, "4 4"]:
def T_opencv_to_opengl(
T: Float[np.ndarray, "4 4"]
) -> Float[np.ndarray, "4 4"]:
"""
Convert T from OpenCV convention to OpenGL convention.
Expand Down Expand Up @@ -267,7 +281,9 @@ def T_opencv_to_opengl(T: Float[np.ndarray, "4 4"]) -> Float[np.ndarray, "4 4"]:
return T


def pose_opengl_to_opencv(pose: Float[np.ndarray, "4 4"]) -> Float[np.ndarray, "4 4"]:
def pose_opengl_to_opencv(
pose: Float[np.ndarray, "4 4"]
) -> Float[np.ndarray, "4 4"]:
"""
Convert pose from OpenGL convention to OpenCV convention.
Expand All @@ -292,7 +308,9 @@ def pose_opengl_to_opencv(pose: Float[np.ndarray, "4 4"]) -> Float[np.ndarray, "
return pose


def pose_opencv_to_opengl(pose: Float[np.ndarray, "4 4"]) -> Float[np.ndarray, "4 4"]:
def pose_opencv_to_opengl(
pose: Float[np.ndarray, "4 4"]
) -> Float[np.ndarray, "4 4"]:
"""
Convert pose from OpenCV convention to OpenGL convention.
Expand Down Expand Up @@ -446,7 +464,9 @@ def T_to_R_t(

def P_to_K_R_t(
P: Float[np.ndarray, "3 4"],
) -> Tuple[Float[np.ndarray, "3 3"], Float[np.ndarray, "3 3"], Float[np.ndarray, "3"]]:
) -> Tuple[
Float[np.ndarray, "3 3"], Float[np.ndarray, "3 3"], Float[np.ndarray, "3"]
]:
"""
Decompose projection matrix P into intrinsic matrix K, rotation matrix R,
and translation vector t.
Expand Down Expand Up @@ -785,7 +805,9 @@ def mesh_to_lineset(

if color is not None:
if len(color) != 3:
raise ValueError(f"Expected color of shape (3,), but got {color.shape}.")
raise ValueError(
f"Expected color of shape (3,), but got {color.shape}."
)
lineset.paint_uniform_color(color)

return lineset
Expand Down
4 changes: 3 additions & 1 deletion camtools/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ def mesh_to_lineset(
"""
# Downsample mesh
if downsample_ratio < 1.0:
target_number_of_triangles = int(len(mesh.triangles) * downsample_ratio)
target_number_of_triangles = int(
len(mesh.triangles) * downsample_ratio
)
mesh = mesh.simplify_quadric_decimation(target_number_of_triangles)
elif downsample_ratio > 1.0:
raise ValueError("Subsample must be less than or equal to 1.0")
Expand Down
Loading

0 comments on commit a81124a

Please sign in to comment.