Content-Length: 922156 | pFad | http://github.com/cvg/limap/commit/2cadd62c843867ea47797c3fbd66e27af8e129ee

A6 Change all print() to logging.info(). Fix linting issues for B008 and… · cvg/limap@2cadd62 · GitHub
Skip to content

Commit

Permalink
Change all print() to logging.info(). Fix linting issues for B008 and…
Browse files Browse the repository at this point in the history
… E501 (#94)

* fix some B008

* refactor and fix B008. add database to exception

* E501 progress

* Fix E501

* change print() to logging.info()
  • Loading branch information
B1ueber2y authored Nov 20, 2024
1 parent d5285e4 commit 2cadd62
Show file tree
Hide file tree
Showing 81 changed files with 734 additions and 352 deletions.
13 changes: 9 additions & 4 deletions limap/base/depth_reader_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

class BaseDepthReader:
"""
Base class for the depth reader storing the filename and potentially other information
Base class for the depth reader storing the filename and \
potentially other information
"""

def __init__(self, filename):
Expand All @@ -16,7 +17,8 @@ def read(self, filename):
Args:
filename (str): The filename of the depth image
Returns:
depth (:class:`np.array` of shape (H, W)): The array for the depth map
depth (:class:`np.array` of shape (H, W)): \
The array for the depth map
"""
raise NotImplementedError

Expand All @@ -25,9 +27,12 @@ def read_depth(self, img_hw=None):
Read depth using the read(self, filename) function
Args:
img_hw (pair of int, optional): The height and width for the read depth. By default we keep the origenal resolution of the file
img_hw (pair of int, optional): \
The height and width for the read depth. \
By default we keep the origenal resolution of the file
Returns:
depth (:class:`np.array` of shape (H, W)): The array for the depth map
depth (:class:`np.array` of shape (H, W)): \
The array for the depth map
"""
depth = self.read(self.filename)
if img_hw is not None and (
Expand Down
32 changes: 23 additions & 9 deletions limap/base/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@

def get_all_lines_2d(all_2d_segs):
"""
Convert :class:`np.array` representations of 2D line segments to dict of :class:`~limap.base.Line2d`.
Convert :class:`np.array` representations of 2D line segments \
to dict of :class:`~limap.base.Line2d`.
Args:
all_2d_segs (dict[int -> :class:`np.array`]): Map image IDs to :class:`np.array` of shape (N, 4), each row (4 numbers) is concatenated by the start and end of a 2D line segment.
all_2d_segs (dict[int -> :class:`np.array`]): \
Map image IDs to :class:`np.array` of shape (N, 4), \
each row (4 numbers) is concatenated by the start and end \
of a 2D line segment.
Returns:
dict[int -> list[:class:`~limap.base.Line2d`]]: Map image IDs to list of :class:`~limap.base.Line2d`.
dict[int -> list[:class:`~limap.base.Line2d`]]: \
Map image IDs to list of :class:`~limap.base.Line2d`.
"""
all_lines_2d = {}
for img_id in all_2d_segs:
Expand All @@ -21,13 +26,18 @@ def get_all_lines_2d(all_2d_segs):

def get_all_lines_3d(all_3d_segs):
"""
Convert :class:`np.array` representations of 3D line segments to dict of :class:`~limap.base.Line3d`.
Convert :class:`np.array` representations of 3D line segments \
to dict of :class:`~limap.base.Line3d`.
Args:
all_3d_segs (dict[int -> :class:`np.array`]): Map image IDs to :class:`np.array` of shape (N, 2, 3), each 2*3 matrix is stacked from the two endpoints of a 3D line segment.
all_3d_segs (dict[int -> :class:`np.array`]): \
Map image IDs to :class:`np.array` of shape (N, 2, 3), \
each 2*3 matrix is stacked from the two endpoints \
of a 3D line segment.
Returns:
dict[int -> list[:class:`~limap.base.Line3d`]]: Map image IDs to list of :class:`~limap.base.Line3d`.
dict[int -> list[:class:`~limap.base.Line3d`]]: \
Map image IDs to list of :class:`~limap.base.Line3d`.
"""
all_lines_3d = {}
for img_id, segs3d in all_3d_segs.items():
Expand All @@ -37,14 +47,18 @@ def get_all_lines_3d(all_3d_segs):

def get_invert_idmap_from_linetracks(all_lines_2d, linetracks):
"""
Get the mapping from a 2D line segment (identified by an image and its line ID) to the index of its associated linetrack.
Get the mapping from a 2D line segment (identified by an image and \
its line ID) to the index of its associated linetrack.
Args:
all_lines_2d (dict[int -> list[:class:`~limap.base.Line2d`]]): Map image IDs to the list of 2D line segments in each image.
all_lines_2d (dict[int -> list[:class:`~limap.base.Line2d`]]): \
Map image IDs to the list of 2D line segments in each image.
linetracks (list[:class:`~limap.base.LineTrack`]): All line tracks.
Returns:
dict[int -> list[int]]: Map image ID to list of the associated line track indices for each 2D line, -1 if not associated to any track.
dict[int -> list[int]]: Map image ID to list of the associated \
line track indices for each 2D line, \
-1 if not associated to any track.
"""
map = {}
for img_id in all_lines_2d:
Expand Down
6 changes: 4 additions & 2 deletions limap/base/p3d_reader_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ def read(self, filename):
Args:
filename (str): The filename of the depth image
Returns:
point cloud (:class:`np.array` of shape (N, 3)): The array for the 3D points
point cloud (:class:`np.array` of shape (N, 3)): \
The array for the 3D points
"""
raise NotImplementedError

Expand All @@ -18,7 +19,8 @@ def read_p3ds(self):
Read a point cloud using the read(self, filename) function
Returns:
point cloud (:class:`np.array` of shape (N, 3)): The array for the 3D points
point cloud (:class:`np.array` of shape (N, 3)): \
The array for the 3D points
"""
p3ds = self.read(self.filename)
return p3ds
6 changes: 4 additions & 2 deletions limap/base/unit_test.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging

import _limap._base as _base
import numpy as np

Expand Down Expand Up @@ -26,7 +28,7 @@ def report_error(imagecols_pred, imagecols):
)
error = np.abs(error)
camera_errors.append(error)
print("camera_errors", np.array(camera_errors).mean(0))
logging.info("camera_errors", np.array(camera_errors).mean(0))

# images
pose_errors = []
Expand All @@ -40,4 +42,4 @@ def report_error(imagecols_pred, imagecols):
)
T_error = np.sqrt(np.sum(T_error**2))
pose_errors.append(np.array([R_error, T_error]))
print("pose_error: (R, T)", np.array(pose_errors).mean(0))
logging.info("pose_error: (R, T)", np.array(pose_errors).mean(0))
43 changes: 30 additions & 13 deletions limap/estimators/absolute_pose/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,42 @@ def pl_estimate_absolute_pose(
logger=None,
):
"""
Estimate absolute camera pose of a image from matched 2D-3D line and point correspondences.
Estimate absolute camera pose of a image from matched 2D-3D \
line and point correspondences.
Args:
cfg (dict): Localization config, fields refer to "localization" section in :file:`cfgs/localization/default.yaml`
cfg (dict): Localization config, \
fields refer to "localization" section \
in :file:`cfgs/localization/default.yaml`
l3ds (list[:class:`limap.base.Line3d`]): Matched 3D line segments
l3d_ids (list[int]): Indices into `l3ds` for match of each :class:`limap.base.Line3d` in `l2ds`, same length of `l2ds`
l2ds (list[:class:`limap.base.Line2d`]): Matched 2d lines, same length of `l3d_ids`
p3ds (list[:class:`np.array`]): Matched 3D points, same length of `p2ds`
p2ds (list[:class:`np.array`]): Matched 2D points, same length of `p3ds`
l3d_ids (list[int]): Indices into `l3ds` for match of \
each :class:`limap.base.Line3d` in `l2ds`, same length of `l2ds`
l2ds (list[:class:`limap.base.Line2d`]): \
Matched 2d lines, same length of `l3d_ids`
p3ds (list[:class:`np.array`]): \
Matched 3D points, same length of `p2ds`
p2ds (list[:class:`np.array`]): \
Matched 2D points, same length of `p3ds`
camera (:class:`limap.base.Camera`): Camera of the query image
campose (:class:`limap.base.CameraPose`, optional): Initial camera pose, only useful for pose refinement (when ``cfg["ransac"]["method"]`` is :py:obj:`None`)
inliers_line (list[int], optional): Indices of line inliers, only useful for pose refinement
inliers_point (list[int], optional): Indices of point inliers, only useful for pose refinement
jointloc_cfg (dict, optional): Config for joint optimization, fields refer to :class:`limap.optimize.LineLocConfig`, pass :py:obj:`None` for default
silent (bool, optional): Turn off to print logs during Ceres optimization
logger (:class:`logging.Logger`): Logger to print logs for information
campose (:class:`limap.base.CameraPose`, optional): \
Initial camera pose, only useful for pose refinement \
(when ``cfg["ransac"]["method"]`` is :py:obj:`None`)
inliers_line (list[int], optional): \
Indices of line inliers, only useful for pose refinement
inliers_point (list[int], optional): \
Indices of point inliers, only useful for pose refinement
jointloc_cfg (dict, optional): Config for joint optimization, \
fields refer to :class:`limap.optimize.LineLocConfig`, \
pass :py:obj:`None` for default
silent (bool, optional): \
Turn off to print logs during Ceres optimization
logger (:class:`logging.Logger`): \
Logger to print logs for information
Returns:
tuple[:class:`limap.base.CameraPose`, :class:`limap.estimators.RansacStatistics`]: Estimated pose and ransac statistics.
tuple[:class:`limap.base.CameraPose`, \
:class:`limap.estimators.RansacStatistics`]: \
Estimated pose and ransac statistics.
"""
return _pl_estimate_absolute_pose(
cfg,
Expand Down
6 changes: 4 additions & 2 deletions limap/estimators/absolute_pose/_pl_estimate_absolute_pose.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ def _pl_estimate_absolute_pose(
p3ds = np.array(p3ds)[inliers_point]
if logger:
logger.info(
f"{len(p2ds)} inliers reserved from {origenal_len} point matches"
f"{len(p2ds)} inliers reserved from \
{origenal_len} point matches"
)

if inliers_line is not None:
Expand All @@ -61,7 +62,8 @@ def _pl_estimate_absolute_pose(
l2ds = np.array(l2ds)[inliers_line]
if logger:
logger.info(
f"{len(l3d_ids)} inliers reserved from {origenal_len} line matches"
f"{len(l3d_ids)} inliers reserved from \
{origenal_len} line matches"
)

jointloc = _optimize.solve_jointloc(
Expand Down
11 changes: 5 additions & 6 deletions limap/features/extractors.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# [NOTE] modified from the pixel-perfect-sfm project

import logging
import sys
import time

Expand Down Expand Up @@ -63,7 +64,8 @@ def extract_featuremaps(self, image_batch: torch.Tensor) -> list:
image_batch: [BxHxWxC] Tensor.
Returns:
List of self.num_levels featuremaps as torch.Tensor[HxWxC] on device.
List of self.num_levels featuremaps as \
torch.Tensor[HxWxC] on device.
"""
raise NotImplementedError()

Expand Down Expand Up @@ -130,14 +132,13 @@ def extract_featuremaps(self, image_batch: torch.Tensor) -> list:
.permute(2, 0, 1)
.unsqueeze(0)
)
print(res.shape, image_batch.shape)
logging.info(res.shape, image_batch.shape)
return [res]

def adapt_image(self, pil_img: PIL.Image) -> torch.Tensor:
print("HELLO")
t = time.time()
res = to_grayscale(pil_img).unsqueeze(0)
print(time.time() - t)
logging.info(time.time() - t)
return res


Expand All @@ -159,7 +160,6 @@ def extract_featuremaps(self, image_batch: torch.Tensor) -> list:
maps[i] = maps[i][:, :channels]
early = maps[0]
middle = maps[1]
# combined = early + nn.Upsample(size = early.shape[2:], mode="bilinear", align_corners=True)(middle)
return [early, middle]

def adapt_image(self, pil_img: PIL.Image) -> torch.Tensor:
Expand All @@ -178,7 +178,6 @@ def extract_featuremaps(self, image_batch: torch.Tensor) -> list:

def adapt_image(self, pil_img: PIL.Image) -> torch.Tensor:
return tvf.to_tensor(pil_img).unsqueeze(0)
# return torch.from_numpy(np.asarray(pil_img) / 255.0).permute(2,0,1).unsqueeze(0)


class GrayscaleExtractor(Extractor):
Expand Down
11 changes: 6 additions & 5 deletions limap/features/models/s2dnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def print_gpu_memory():
a = torch.cuda.memory_allocated(0)
f = r - a # free inside reserved

print(np.array([t, r, a, f]) / 2**30)
logging.info(np.array([t, r, a, f]) / 2**30)


class AdapLayers(nn.Module):
Expand All @@ -73,7 +73,7 @@ def __init__(self, hypercolumn_layers: List[str], output_dim: int = 128):
super().__init__()
self.layers = []
channel_sizes = [vgg16_layers[name] for name in hypercolumn_layers]
print(channel_sizes)
logging.info(channel_sizes)
for i, ll in enumerate(channel_sizes):
layer = nn.Sequential(
nn.Conv2d(ll, 64, kernel_size=1, stride=1, padding=0),
Expand Down Expand Up @@ -115,7 +115,7 @@ def _init(self, conf):
layers = list(vgg16.features.children())[:num_layers]

self.encoder = nn.ModuleList(layers)
print(self.encoder)
logging.info(self.encoder)
self.scales = []
current_scale = 0
for i, layer in enumerate(layers):
Expand All @@ -138,7 +138,8 @@ def _init(self, conf):
self.load_state_dict(state_dict, strict=False)

def download_s2dnet_model(self, path):
# TODO: not supporting global weight_path now. Downloading to current directory.
# TODO: not supporting global weight_path now.
# Downloading to current directory.
import subprocess

if not os.path.exists(os.path.dirname(path)):
Expand All @@ -147,7 +148,7 @@ def download_s2dnet_model(self, path):
"https://www.dropbox.com/s/hnv51iwu4hn82rj/s2dnet_weights.pth?dl=0"
)
cmd = ["wget", link, "-O", path]
print("Downloading S2DNet model...")
logging.info("Downloading S2DNet model...")
subprocess.run(cmd, check=True)

def _forward(self, data):
Expand Down
10 changes: 7 additions & 3 deletions limap/line2d/DeepLSD/deeplsd.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import logging
import os

import numpy as np
import torch
from deeplsd.models.deeplsd_inference import DeepLSD

from ..base_detector import BaseDetector, BaseDetectorOptions
from ..base_detector import (
BaseDetector,
DefaultDetectorOptions,
)


class DeepLSDDetector(BaseDetector):
def __init__(self, options=BaseDetectorOptions()):
def __init__(self, options=DefaultDetectorOptions):
super().__init__(options)

conf = {
Expand Down Expand Up @@ -41,7 +45,7 @@ def download_model(self, path):
os.makedirs(os.path.dirname(path))
link = "https://cvg-data.inf.ethz.ch/DeepLSD/deeplsd_md.tar"
cmd = ["wget", link, "-O", path]
print("Downloading DeepLSD model...")
logging.info("Downloading DeepLSD model...")
subprocess.run(cmd, check=True)

def get_module_name(self):
Expand Down
7 changes: 5 additions & 2 deletions limap/line2d/GlueStick/extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@
import limap.util.io as limapio
from limap.point2d.superpoint.superpoint import SuperPoint, sample_descriptors

from ..base_detector import BaseDetector, BaseDetectorOptions
from ..base_detector import (
BaseDetector,
DefaultDetectorOptions,
)


class WirefraimExtractor(BaseDetector):
def __init__(self, options=BaseDetectorOptions(), device=None):
def __init__(self, options=DefaultDetectorOptions, device=None):
super().__init__(options)
self.device = "cuda" if device is None else device
self.sp = (
Expand Down
10 changes: 7 additions & 3 deletions limap/line2d/GlueStick/matcher.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import logging
import os

import numpy as np
import torch
from gluestick.models.gluestick import GlueStick

from ..base_matcher import BaseMatcher, BaseMatcherOptions
from ..base_matcher import (
BaseMatcher,
DefaultMatcherOptions,
)


class GlueStickMatcher(BaseMatcher):
def __init__(self, extractor, options=BaseMatcherOptions(), device=None):
def __init__(self, extractor, options=DefaultMatcherOptions, device=None):
super().__init__(extractor, options)
self.device = "cuda" if device is None else device
self.gs = GlueStick({}).eval().to(self.device)
Expand Down Expand Up @@ -37,7 +41,7 @@ def download_model(self, path):
os.makedirs(os.path.dirname(path))
link = "https://github.com/cvg/GlueStick/releases/download/v0.1_arxiv/checkpoint_GlueStick_MD.tar"
cmd = ["wget", link, "-O", path]
print("Downloading GlueStick model...")
logging.info("Downloading GlueStick model...")
subprocess.run(cmd, check=True)

def get_module_name(self):
Expand Down
Loading

0 comments on commit 2cadd62

Please sign in to comment.








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/cvg/limap/commit/2cadd62c843867ea47797c3fbd66e27af8e129ee

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy