From 64530fc29ef5fa799eeaabf57565d0570d750285 Mon Sep 17 00:00:00 2001 From: Shaohui Liu Date: Sat, 19 Oct 2024 23:39:27 +0200 Subject: [PATCH] Fix some linting issues (#90) * Fix SIM113 * All SIM error fixed * fix B007. * fix E402. * fix E741. * minor. * move B904 to file-specific. * fix B028. * file-specific UP031. * fix E722. * minor. * minor. * fix s2dnet and vggnet linting. * fix s2dnet linting. * specific. --------- Co-authored-by: Yifan Yu --- limap/base/align.py | 4 +- limap/features/models/s2dnet.py | 7 +- limap/features/models/vggnet.py | 3 +- limap/line2d/L2D2/RAL_net_cov.py | 3 +- limap/line2d/L2D2/extractor.py | 4 +- limap/line2d/LBD/extractor.py | 6 +- limap/line2d/LineTR/line_transformer.py | 7 +- limap/line2d/SOLD2/model/metrics.py | 4 +- .../line2d/SOLD2/model/nets/lcnn_hourglass.py | 6 +- limap/line2d/SOLD2/train.py | 2 +- limap/optimize/functions.py | 5 -- .../line_refinement/line_refinement.py | 2 +- limap/point2d/superglue/superglue.py | 4 +- limap/point2d/superpoint/main.py | 9 ++- limap/pointsfm/bundler_reader.py | 4 +- limap/pointsfm/colmap_sfm.py | 4 +- limap/pointsfm/model_converter.py | 9 ++- limap/pointsfm/visualsfm_reader.py | 4 +- limap/runners/functions.py | 6 +- limap/runners/line_fitnmerge.py | 6 +- limap/runners/line_triangulation.py | 2 +- limap/triangulation/triangulation.py | 4 +- limap/util/io.py | 10 +-- limap/visualize/trackvis/pyvista.py | 2 +- limap/visualize/vis_bipartite.py | 4 +- limap/visualize/vis_matches.py | 32 ++++----- limap/visualize/vis_utils.py | 68 +++++++++++-------- ruff.toml | 16 ++--- runners/cambridge/utils.py | 4 +- runners/tests/line2d.py | 4 +- scripts/tnt_align.py | 12 ++-- 31 files changed, 129 insertions(+), 128 deletions(-) diff --git a/limap/base/align.py b/limap/base/align.py index 072fabaf..21bb57a8 100644 --- a/limap/base/align.py +++ b/limap/base/align.py @@ -130,8 +130,8 @@ def read_trans(fname): lines = f.readlines() mat = [] for idx in range(4): - l = lines[idx].strip("\n").split() - mat.append([float(k) for k in l]) + line = lines[idx].strip("\n").split() + mat.append([float(k) for k in line]) mat = np.array(mat) assert np.all(mat[3, :] == np.array([0, 0, 0, 1])) return mat[:3, :] diff --git a/limap/features/models/s2dnet.py b/limap/features/models/s2dnet.py index 3fd0cf0b..c33ff819 100644 --- a/limap/features/models/s2dnet.py +++ b/limap/features/models/s2dnet.py @@ -70,13 +70,13 @@ def __init__(self, hypercolumn_layers: List[str], output_dim: int = 128): hypercolumn_layers: The list of the hypercolumn layer names. output_dim: The output channel dimension. """ - super(AdapLayers, self).__init__() + super().__init__() self.layers = [] channel_sizes = [vgg16_layers[name] for name in hypercolumn_layers] print(channel_sizes) - for i, l in enumerate(channel_sizes): + for i, ll in enumerate(channel_sizes): layer = nn.Sequential( - nn.Conv2d(l, 64, kernel_size=1, stride=1, padding=0), + nn.Conv2d(ll, 64, kernel_size=1, stride=1, padding=0), nn.ReLU(), nn.Conv2d(64, output_dim, kernel_size=5, stride=1, padding=2), nn.BatchNorm2d(output_dim), @@ -134,7 +134,6 @@ def _init(self, conf): self.download_s2dnet_model(path) logging.info(f"Loading S2DNet checkpoint at {path}.") state_dict = torch.load(path, map_location="cpu")["state_dict"] - params = self.state_dict() state_dict = {k: v for k, v in state_dict.items()} self.load_state_dict(state_dict, strict=False) diff --git a/limap/features/models/vggnet.py b/limap/features/models/vggnet.py index fee891cc..7dbc3ea5 100644 --- a/limap/features/models/vggnet.py +++ b/limap/features/models/vggnet.py @@ -2,7 +2,8 @@ import torch.nn as nn import torchvision.models as models -from limap.features.models.s2dnet import * +from .base_model import BaseModel +from .s2dnet import vgg16_layers class VGGNet(BaseModel): diff --git a/limap/line2d/L2D2/RAL_net_cov.py b/limap/line2d/L2D2/RAL_net_cov.py index cf215372..98375542 100644 --- a/limap/line2d/L2D2/RAL_net_cov.py +++ b/limap/line2d/L2D2/RAL_net_cov.py @@ -68,8 +68,7 @@ def weights_init(m): nn.init.orthogonal_(m.weight.data, gain=0.6) try: nn.init.constant_(m.bias.data, 0.01) - - except: + except AttributeError: pass return diff --git a/limap/line2d/L2D2/extractor.py b/limap/line2d/L2D2/extractor.py index d0e3f0ca..4820d9e8 100644 --- a/limap/line2d/L2D2/extractor.py +++ b/limap/line2d/L2D2/extractor.py @@ -123,8 +123,8 @@ def compute_descinfo(self, img, segs): return {"line_descriptors": np.empty((0, 128))} patches, line_desc = [], [] - for i, l in enumerate(lines): - patches.append(self.get_patch(img, l)) + for i, line in enumerate(lines): + patches.append(self.get_patch(img, line)) if (i + 1) % self.mini_batch == 0 or i == len(lines) - 1: # Extract the descriptors diff --git a/limap/line2d/LBD/extractor.py b/limap/line2d/LBD/extractor.py index 46456f90..58abe9fc 100644 --- a/limap/line2d/LBD/extractor.py +++ b/limap/line2d/LBD/extractor.py @@ -18,7 +18,7 @@ def process_pyramid( cur_sigma2 = 1.0 pyramid = [] multiscale_segs = [] - for i in range(n_levels): + for _ in range(n_levels): increase_sigma = np.sqrt(cur_sigma2 - pre_sigma2) blurred = cv2.GaussianBlur( octave_img, (5, 5), increase_sigma, borderType=cv2.BORDER_REPLICATE @@ -47,8 +47,8 @@ def process_pyramid( def to_multiscale_lines(lines): ms_lines = [] - for l in lines.reshape(-1, 4): - ll = np.append(l, [0, np.linalg.norm(l[:2] - l[2:4])]) + for line in lines.reshape(-1, 4): + ll = np.append(line, [0, np.linalg.norm(line[:2] - line[2:4])]) ms_lines.append( [(0, ll)] + [(i, ll / (i * np.sqrt(2))) for i in range(1, 5)] ) diff --git a/limap/line2d/LineTR/line_transformer.py b/limap/line2d/LineTR/line_transformer.py index 80bcbddf..348fd05c 100755 --- a/limap/line2d/LineTR/line_transformer.py +++ b/limap/line2d/LineTR/line_transformer.py @@ -210,10 +210,10 @@ def __init__(self, num_heads: int, d_model: int): def forward(self, query, key, value): batch_dim = query.size(0) query, key, value = ( - l(x).view( + layer(x).view( batch_dim, self.dim, self.num_heads, -1 ) # [3, 64, 4, 512] - for l, x in zip(self.proj, (query, key, value)) + for layer, x in zip(self.proj, (query, key, value)) ) x, prob = attention(query, key, value) return ( @@ -257,7 +257,8 @@ def __init__(self, feature_dim: int, layer_names: list): def forward(self, kline_desc): d_desc_kline = kline_desc.size(2) - for layer, name in zip(self.layers, self.names): + for layer in self.layers: + # for layer, name in zip(self.layers, self.names): delta, _ = layer(kline_desc, kline_desc) kline_desc = kline_desc + delta diff --git a/limap/line2d/SOLD2/model/metrics.py b/limap/line2d/SOLD2/model/metrics.py index 8b697289..d59649a9 100644 --- a/limap/line2d/SOLD2/model/metrics.py +++ b/limap/line2d/SOLD2/model/metrics.py @@ -577,7 +577,7 @@ def nms_fast(in_corners, H, W, dist_thresh): out = np.vstack((rcorners, in_corners[2])).reshape(3, 1) return out, np.zeros(1).astype(int) # Initialize the grid. - for i, rc in enumerate(rcorners.T): + for i, _ in enumerate(rcorners.T): grid[rcorners[1, i], rcorners[0, i]] = 1 inds[rcorners[1, i], rcorners[0, i]] = i # Pad the border of the grid, so that we can NMS points near the border. @@ -585,7 +585,7 @@ def nms_fast(in_corners, H, W, dist_thresh): grid = np.pad(grid, ((pad, pad), (pad, pad)), mode="constant") # Iterate through points, highest to lowest conf, suppress neighborhood. count = 0 - for i, rc in enumerate(rcorners.T): + for rc in rcorners.T: # Account for top and left padding. pt = (rc[0] + pad, rc[1] + pad) if grid[pt[1], pt[0]] == 1: # If not yet suppressed. diff --git a/limap/line2d/SOLD2/model/nets/lcnn_hourglass.py b/limap/line2d/SOLD2/model/nets/lcnn_hourglass.py index b4259064..41918a68 100644 --- a/limap/line2d/SOLD2/model/nets/lcnn_hourglass.py +++ b/limap/line2d/SOLD2/model/nets/lcnn_hourglass.py @@ -81,7 +81,7 @@ def __init__(self, block, num_blocks, planes, depth): def _make_residual(self, block, num_blocks, planes): layers = [] - for i in range(0, num_blocks): + for _ in range(0, num_blocks): layers.append(block(planes * block.expansion, planes)) return nn.Sequential(*layers) @@ -89,7 +89,7 @@ def _make_hour_glass(self, block, num_blocks, planes, depth): hg = [] for i in range(depth): res = [] - for j in range(3): + for _ in range(3): res.append(self._make_residual(block, num_blocks, planes)) if i == 0: res.append(self._make_residual(block, num_blocks, planes)) @@ -183,7 +183,7 @@ def _make_residual(self, block, planes, blocks, stride=1): layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion - for i in range(1, blocks): + for _ in range(1, blocks): layers.append(block(self.inplanes, planes)) return nn.Sequential(*layers) diff --git a/limap/line2d/SOLD2/train.py b/limap/line2d/SOLD2/train.py index 42f20821..87c4e388 100644 --- a/limap/line2d/SOLD2/train.py +++ b/limap/line2d/SOLD2/train.py @@ -40,7 +40,7 @@ def restore_weights(model, state_dict, strict=True): try: model.load_state_dict(state_dict, strict=strict) # Deal with some version compatibility issue (catch version incompatible) - except: + except KeyError: err = model.load_state_dict(state_dict, strict=False) # missing keys are those in model but not in state_dict diff --git a/limap/optimize/functions.py b/limap/optimize/functions.py index 70dec61f..45a11899 100644 --- a/limap/optimize/functions.py +++ b/limap/optimize/functions.py @@ -1,11 +1,6 @@ -import os - -import cv2 import numpy as np -from tqdm import tqdm import limap.base as _base -import limap.visualize as limapvis def unit_test_add_noise_to_track(track): diff --git a/limap/optimize/line_refinement/line_refinement.py b/limap/optimize/line_refinement/line_refinement.py index 413a5697..4484a1d1 100644 --- a/limap/optimize/line_refinement/line_refinement.py +++ b/limap/optimize/line_refinement/line_refinement.py @@ -114,7 +114,7 @@ def line_refinement( # output newtracks = [] counter = 0 - for idx, track in enumerate(tracks): + for track in tracks: if track.count_images() < n_visible_views: newtracks.append(track) else: diff --git a/limap/point2d/superglue/superglue.py b/limap/point2d/superglue/superglue.py index 8610d1d8..f356a1b7 100644 --- a/limap/point2d/superglue/superglue.py +++ b/limap/point2d/superglue/superglue.py @@ -112,8 +112,8 @@ def forward( ) -> torch.Tensor: batch_dim = query.size(0) query, key, value = ( - l(x).view(batch_dim, self.dim, self.num_heads, -1) - for l, x in zip(self.proj, (query, key, value)) + layer(x).view(batch_dim, self.dim, self.num_heads, -1) + for layer, x in zip(self.proj, (query, key, value)) ) x, _ = attention(query, key, value) return self.merge( diff --git a/limap/point2d/superpoint/main.py b/limap/point2d/superpoint/main.py index 47fe72b5..84a3b7f1 100644 --- a/limap/point2d/superpoint/main.py +++ b/limap/point2d/superpoint/main.py @@ -1,3 +1,4 @@ +import collections.abc as collections import pprint from pathlib import Path from typing import Dict, List, Optional, Union @@ -5,16 +6,14 @@ import h5py import numpy as np import torch -from tqdm import tqdm - -string_classes = str -import collections.abc as collections - from hloc import extract_features from hloc.utils.io import list_h5_names +from tqdm import tqdm from .superpoint import SuperPoint +string_classes = str + # Copy from legacy hloc code def map_tensor(input_, func): diff --git a/limap/pointsfm/bundler_reader.py b/limap/pointsfm/bundler_reader.py index 8e402b7f..881c5467 100644 --- a/limap/pointsfm/bundler_reader.py +++ b/limap/pointsfm/bundler_reader.py @@ -88,7 +88,7 @@ def ReadModelBundler(bundler_path, list_path, model_path): imagecols = _base.ImageCollection(cameras, camimages) # read points - for point_id in tqdm(range(n_points)): + for _ in tqdm(range(n_points)): line = lines[counter].strip("\n").split(" ") x, y, z = float(line[0]), float(line[1]), float(line[2]) counter += 1 @@ -97,7 +97,7 @@ def ReadModelBundler(bundler_path, list_path, model_path): n_views = int(line[0]) subcounter = 1 track = [] - for view_id in range(n_views): + for _ in range(n_views): track.append(int(line[subcounter])) subcounter += 4 model.addPoint(x, y, z, track) diff --git a/limap/pointsfm/colmap_sfm.py b/limap/pointsfm/colmap_sfm.py index ec7941cd..e6d42bc3 100644 --- a/limap/pointsfm/colmap_sfm.py +++ b/limap/pointsfm/colmap_sfm.py @@ -172,7 +172,7 @@ def run_colmap_sfm( ### copy images to tmp folder keypoints_in_order = [] - for idx, img_id in enumerate(imagecols.get_img_ids()): + for img_id in imagecols.get_img_ids(): img = imagecols.read_image(img_id) fname_to_save = os.path.join(image_path, f"image{img_id:08d}.png") cv2.imwrite(fname_to_save, img) @@ -247,7 +247,7 @@ def run_colmap_sfm_with_known_poses( ### copy images to tmp folder keypoints_in_order = [] imagecols_tmp = copy.deepcopy(imagecols) - for idx, img_id in enumerate(imagecols.get_img_ids()): + for img_id in imagecols.get_img_ids(): img = imagecols.read_image(img_id) fname_to_save = os.path.join(image_path, f"image{img_id:08d}.png") cv2.imwrite(fname_to_save, img) diff --git a/limap/pointsfm/model_converter.py b/limap/pointsfm/model_converter.py index cbed2cbc..ab3f2f30 100644 --- a/limap/pointsfm/model_converter.py +++ b/limap/pointsfm/model_converter.py @@ -21,10 +21,9 @@ def convert_colmap_to_visualsfm(colmap_model_path, output_nvm_file): # write images f.write(f"{len(colmap_images)}\n") map_image_id = dict() - counter = 0 - for img_id, colmap_image in colmap_images.items(): - map_image_id[img_id] = counter - counter += 1 + for cnt, item in enumerate(colmap_images.items()): + img_id, colmap_image = item + map_image_id[img_id] = cnt img_name = colmap_image.name cam_id = colmap_image.camera_id cam = colmap_cameras[cam_id] @@ -58,7 +57,7 @@ def convert_colmap_to_visualsfm(colmap_model_path, output_nvm_file): # write points f.write(f"{len(colmap_points)}\n") - for pid, point in colmap_points.items(): + for _, point in colmap_points.items(): xyz = point.xyz f.write(f"{xyz[0]} {xyz[1]} {xyz[2]}") f.write(" 128 128 128") # dummy color diff --git a/limap/pointsfm/visualsfm_reader.py b/limap/pointsfm/visualsfm_reader.py index 706d5c28..872149c2 100644 --- a/limap/pointsfm/visualsfm_reader.py +++ b/limap/pointsfm/visualsfm_reader.py @@ -69,7 +69,7 @@ def ReadModelVisualSfM(vsfm_path, nvm_file="reconstruction.nvm"): counter += 1 n_points = int(txt_lines[counter].strip()) counter += 1 - for point_id in tqdm(range(n_points)): + for _ in tqdm(range(n_points)): line = txt_lines[counter].strip().split() counter += 1 point = np.array([float(line[k]) for k in range(3)]) @@ -77,7 +77,7 @@ def ReadModelVisualSfM(vsfm_path, nvm_file="reconstruction.nvm"): n_views = int(line[6]) track = [] subcounter = 7 - for view_in in range(n_views): + for _ in range(n_views): track.append(int(line[subcounter])) subcounter += 4 model.addPoint(point[0], point[1], point[2], track) diff --git a/limap/runners/functions.py b/limap/runners/functions.py index 09bafb74..9c41c294 100644 --- a/limap/runners/functions.py +++ b/limap/runners/functions.py @@ -113,7 +113,7 @@ def process(imagecols, img_id): cam_dict[cam_id] = cam_undistorted imagecols_undistorted.change_camera(cam_id, cam_undistorted) imagecols_undistorted.change_image_name(img_id, imname_out) - for idx, img_id in enumerate(loaded_ids): + for img_id in loaded_ids: imname_out = os.path.join(output_dir, f"image{img_id:08d}.png") cam_id = loaded_imagecols.camimage(img_id).cam_id cam_undistorted = loaded_imagecols.cam(cam_id) @@ -172,7 +172,7 @@ def compute_sfminfos(cfg, imagecols, fname="metainfos.txt"): limapio.check_path(cfg["dir_load"]) fname_load = os.path.join(cfg["dir_load"], fname) neighbors, ranges = limapio.read_txt_metainfos(fname_load) - for img_id, neighbor in neighbors.items(): + for img_id, _ in neighbors.items(): neighbors[img_id] = neighbors[img_id][: cfg["n_neighbors"]] return colmap_output_path, neighbors, ranges @@ -207,7 +207,7 @@ def compute_2d_segs(cfg, imagecols, compute_descinfo=True): import limap.line2d if not imagecols.IsUndistorted(): - warnings.warn("The input images are distorted!") + warnings.warn("The input images are distorted!", stacklevel=2) basedir = os.path.join( "line_detections", cfg["line2d"]["detector"]["method"] ) diff --git a/limap/runners/line_fitnmerge.py b/limap/runners/line_fitnmerge.py index b600186b..75a45b79 100644 --- a/limap/runners/line_fitnmerge.py +++ b/limap/runners/line_fitnmerge.py @@ -31,7 +31,7 @@ def process(all_2d_segs, imagecols, depths, fitting_config, img_id): segs, camview = all_2d_segs[img_id], imagecols.camview(img_id) depth = depths[img_id].read_depth(img_hw=[camview.h(), camview.w()]) seg3d_list_idx = [] - for seg_id, s in enumerate(segs): + for s in segs: seg3d = _fit.estimate_seg3d_from_depth( s, depth, @@ -81,7 +81,7 @@ def process(all_2d_segs, imagecols, p3d_reader, fitting_config, img_id): segs, camview = all_2d_segs[img_id], imagecols.camview(img_id) p3ds = p3d_reader[img_id].read_p3ds() seg3d_list_idx = [] - for seg_id, s in enumerate(segs): + for s in segs: seg3d = _fit.estimate_seg3d_from_points3d( s, p3ds, @@ -150,7 +150,7 @@ def line_fitnmerge(cfg, imagecols, depths, neighbors=None, ranges=None): _, neighbors, ranges = _runners.compute_sfminfos(cfg, imagecols) else: neighbors = imagecols.update_neighbors(neighbors) - for img_id, neighbor in neighbors.items(): + for img_id, _ in neighbors.items(): neighbors[img_id] = neighbors[img_id][: cfg["n_neighbors"]] ########################################################## diff --git a/limap/runners/line_triangulation.py b/limap/runners/line_triangulation.py index 2e766a46..14cadf9f 100644 --- a/limap/runners/line_triangulation.py +++ b/limap/runners/line_triangulation.py @@ -63,7 +63,7 @@ def line_triangulation(cfg, imagecols, neighbors=None, ranges=None): os.path.join(cfg["dir_save"], "metainfos.txt"), neighbors, ranges ) neighbors = imagecols.update_neighbors(neighbors) - for img_id, neighbor in neighbors.items(): + for img_id, _ in neighbors.items(): neighbors[img_id] = neighbors[img_id][: cfg["n_neighbors"]] limapio.save_txt_metainfos( os.path.join(cfg["dir_save"], "metainfos.txt"), neighbors, ranges diff --git a/limap/triangulation/triangulation.py b/limap/triangulation/triangulation.py index baa02264..4b03d34e 100644 --- a/limap/triangulation/triangulation.py +++ b/limap/triangulation/triangulation.py @@ -1,8 +1,8 @@ from _limap import _triangulation as _tri -def get_normal_direction(l, view): - return _tri.get_normal_direction(l, view) +def get_normal_direction(line2d, view): + return _tri.get_normal_direction(line2d, view) def get_direction_from_VP(vp, view): diff --git a/limap/util/io.py b/limap/util/io.py index bbede8b7..304e1e9c 100644 --- a/limap/util/io.py +++ b/limap/util/io.py @@ -121,7 +121,7 @@ def read_txt_metainfos(fname): ranges[0][2], ranges[1][2] = float(k[0]), float(k[1]) counter += 1 neighbors = {} - for idx in range(n_images): + for _ in range(n_images): k = txt_lines[counter].strip().split(",") img_id = int(k[0][6:]) neighbor = [int(kk) for kk in k[1:]] @@ -146,7 +146,7 @@ def read_txt_imname_list(fname): n_images = int(txt_lines[counter].strip().split(",")[1]) counter += 1 imname_list = [] - for img_id in range(n_images): + for _ in range(n_images): imname = txt_lines[counter].strip() imname_list.append(imname) counter += 1 @@ -355,7 +355,7 @@ def read_txt_Line3Dpp(fname): line_counters += n_lines # get line 3d line3d_list = [] - for idx in range(n_lines): + for _ in range(n_lines): infos = [float(k) for k in txt_line[counter : (counter + 6)]] line3d = _base.Line3d(infos[:3], infos[3:]) counter += 6 @@ -365,7 +365,7 @@ def read_txt_Line3Dpp(fname): counter += 1 # collect supports img_id_list, line_id_list, line2d_list = [], [], [] - for supp_id in range(n_supports): + for _ in range(n_supports): img_id = int(txt_line[counter]) counter += 1 line_id = int(txt_line[counter]) @@ -378,7 +378,7 @@ def read_txt_Line3Dpp(fname): line2d_list.append(line2d) track = _base.LineTrack(line3d, img_id_list, line_id_list, line2d_list) linetracks.append(track) - for idx in range(n_lines): + for _ in range(n_lines): line_counts.append(track.count_images()) line_track_id_list.append(len(linetracks) - 1) diff --git a/limap/visualize/trackvis/pyvista.py b/limap/visualize/trackvis/pyvista.py index e43d8eb3..fc9fd288 100644 --- a/limap/visualize/trackvis/pyvista.py +++ b/limap/visualize/trackvis/pyvista.py @@ -40,7 +40,7 @@ def vis_all_lines_image( self.plotter.show() def vis_additional_lines(self, lines, img_hw=(600, 800), width=2): - for track_id, line in enumerate(self.lines): + for line in self.lines: color = "#ff0000" self.plotter.add_lines(line.as_array(), color, width=width) for line in lines: diff --git a/limap/visualize/vis_bipartite.py b/limap/visualize/vis_bipartite.py index bdb181df..87057250 100644 --- a/limap/visualize/vis_bipartite.py +++ b/limap/visualize/vis_bipartite.py @@ -64,7 +64,9 @@ def open3d_draw_bipartite3d_pointline( points_deg3p = [p for p, deg in zip(points, degrees) if deg >= 3] lines = bpt3d.get_line_cloud() if ranges is not None: - lines = [l for l in lines if test_line_inside_ranges(l, ranges)] + lines = [ + line for line in lines if test_line_inside_ranges(line, ranges) + ] # optionally draw edges edges = None diff --git a/limap/visualize/vis_matches.py b/limap/visualize/vis_matches.py index 357b2b99..e281e871 100644 --- a/limap/visualize/vis_matches.py +++ b/limap/visualize/vis_matches.py @@ -72,7 +72,7 @@ def plot_lines( alpha: alpha transparency. """ if not isinstance(line_colors, list): - line_colors = [[line_colors] * len(l) for l in lines] + line_colors = [[line_colors] * len(line) for line in lines] for i in range(len(lines)): if (not isinstance(line_colors[i], list)) and ( not isinstance(line_colors[i], np.ndarray) @@ -86,18 +86,18 @@ def plot_lines( fig.canvas.draw() # Plot the lines and junctions - for a, l, lc in zip(axes, lines, line_colors): - for i in range(len(l)): - line = matplotlib.lines.Line2D( - (l[i, 0, 0], l[i, 1, 0]), - (l[i, 0, 1], l[i, 1, 1]), + for a, line, lc in zip(axes, lines, line_colors): + for i in range(len(line)): + mpl_line = matplotlib.lines.Line2D( + (line[i, 0, 0], line[i, 1, 0]), + (line[i, 0, 1], line[i, 1, 1]), zorder=1, c=lc[i], linewidth=lw, alpha=alpha, ) - a.add_line(line) - pts = l.reshape(-1, 2) + a.add_line(mpl_line) + pts = line.reshape(-1, 2) a.scatter( pts[:, 0], pts[:, 1], @@ -132,11 +132,11 @@ def plot_color_line_matches(lines, correct_matches=None, lw=2, indices=(0, 1)): fig.canvas.draw() # Plot the lines - for a, l in zip(axes, lines): + for a, line in zip(axes, lines): # Transform the points into the figure coordinate system transFigure = fig.transFigure.inverted() - endpoint0 = transFigure.transform(a.transData.transform(l[:, 0])) - endpoint1 = transFigure.transform(a.transData.transform(l[:, 1])) + endpoint0 = transFigure.transform(a.transData.transform(line[:, 0])) + endpoint1 = transFigure.transform(a.transData.transform(line[:, 1])) fig.lines += [ matplotlib.lines.Line2D( (endpoint0[i, 0], endpoint1[i, 0]), @@ -168,7 +168,7 @@ def plot_color_lines( blue = palette[5] # palette[0] red = palette[0] # palette[3] green = palette[2] # palette[2] - colors = [np.array([blue] * len(l)) for l in lines] + colors = [np.array([blue] * len(line)) for line in lines] for i, c in enumerate(colors): c[np.array(correct_matches[i])] = green c[np.array(wrong_matches[i])] = red @@ -180,11 +180,11 @@ def plot_color_lines( fig.canvas.draw() # Plot the lines - for a, l, c in zip(axes, lines, colors): + for a, line, c in zip(axes, lines, colors): # Transform the points into the figure coordinate system transFigure = fig.transFigure.inverted() - endpoint0 = transFigure.transform(a.transData.transform(l[:, 0])) - endpoint1 = transFigure.transform(a.transData.transform(l[:, 1])) + endpoint0 = transFigure.transform(a.transData.transform(line[:, 0])) + endpoint1 = transFigure.transform(a.transData.transform(line[:, 1])) fig.lines += [ matplotlib.lines.Line2D( (endpoint0[i, 0], endpoint1[i, 0]), @@ -194,7 +194,7 @@ def plot_color_lines( c=c[i], linewidth=lw, ) - for i in range(len(l)) + for i in range(len(line)) ] diff --git a/limap/visualize/vis_utils.py b/limap/visualize/vis_utils.py index 13e2927a..6fcedf87 100644 --- a/limap/visualize/vis_utils.py +++ b/limap/visualize/vis_utils.py @@ -70,21 +70,29 @@ def draw_multiscale_segments( img = copy.deepcopy(img) for s in segs: mycolor = random_color() if color is None else color - octave, l = s[0] - l = l * np.sqrt(2) ** octave + octave, line = s[0] + line = line * np.sqrt(2) ** octave cv2.line( img, - (int(l[0]), int(l[1])), - (int(l[2]), int(l[3])), + (int(line[0]), int(line[1])), + (int(line[2]), int(line[3])), mycolor, thickness, ) if endpoints: cv2.circle( - img, (int(l[0]), int(l[1])), int(thickness * 1.5), mycolor, -1 + img, + (int(line[0]), int(line[1])), + int(thickness * 1.5), + mycolor, + -1, ) cv2.circle( - img, (int(l[2]), int(l[3])), int(thickness * 1.5), mycolor, -1 + img, + (int(line[2]), int(line[3])), + int(thickness * 1.5), + mycolor, + -1, ) return img @@ -107,22 +115,22 @@ def draw_multiscale_matches( b1.append(b) line_id_l, line_id_r = matches[pair] - octave, l = segs_left[line_id_l][0] - l = l * np.sqrt(2) ** octave + octave, line = segs_left[line_id_l][0] + line = line * np.sqrt(2) ** octave cv2.line( left_color_img, - (int(l[0]), int(l[1])), - (int(l[2]), int(l[3])), + (int(line[0]), int(line[1])), + (int(line[2]), int(line[3])), (r1[pair], g1[pair], b1[pair]), 3, ) - octave, l = segs_right[line_id_r][0] - l = l * np.sqrt(2) ** octave + octave, line = segs_right[line_id_r][0] + line = line * np.sqrt(2) ** octave cv2.line( right_color_img, - (int(l[0]), int(l[1])), - (int(l[2]), int(l[3])), + (int(line[0]), int(line[1])), + (int(line[2]), int(line[3])), (r1[pair], g1[pair], b1[pair]), 3, ) @@ -160,37 +168,37 @@ def draw_singlescale_matches(img_left, img_right, matched_segs, mask=None): right_color_img = cv2.cvtColor(img_right, cv2.COLOR_GRAY2BGR) colors = [] if mask is None: - for l, r in matched_segs: + for left, right in matched_segs: color = random_color() colors.append(color) cv2.line( left_color_img, - (int(l[0]), int(l[1])), - (int(l[2]), int(l[3])), + (int(left[0]), int(left[1])), + (int(left[2]), int(left[3])), color, 3, ) cv2.line( right_color_img, - (int(r[0]), int(r[1])), - (int(r[2]), int(r[3])), + (int(right[0]), int(right[1])), + (int(right[2]), int(right[3])), color, 3, ) else: - for correct, (l, r) in zip(mask, matched_segs): + for correct, (left, right) in zip(mask, matched_segs): color = (0, 255, 0) if correct else (0, 0, 255) cv2.line( left_color_img, - (int(l[0]), int(l[1])), - (int(l[2]), int(l[3])), + (int(left[0]), int(left[1])), + (int(left[2]), int(left[3])), color, 3, ) cv2.line( right_color_img, - (int(r[0]), int(r[1])), - (int(r[2]), int(r[3])), + (int(right[0]), int(right[1])), + (int(right[2]), int(right[3])), color, 3, ) @@ -199,17 +207,17 @@ def draw_singlescale_matches(img_left, img_right, matched_segs, mask=None): result_img_tmp = result_img.copy() if mask is None: for i in range(len(matched_segs)): - l, r = matched_segs[i] - start_ptn = (int(l[0]), int(l[1])) - end_ptn = (int(r[0] + w), int(r[1])) + left, right = matched_segs[i] + start_ptn = (int(left[0]), int(left[1])) + end_ptn = (int(right[0] + w), int(right[1])) cv2.line( result_img_tmp, start_ptn, end_ptn, colors[i], 2, cv2.LINE_AA ) else: - for correct, (l, r) in zip(mask, matched_segs): + for correct, (left, right) in zip(mask, matched_segs): color = (0, 255, 0) if correct else (0, 0, 255) - start_ptn = (int(l[0]), int(l[1])) - end_ptn = (int(r[0] + w), int(r[1])) + start_ptn = (int(left[0]), int(left[1])) + end_ptn = (int(right[0] + w), int(right[1])) cv2.line(result_img_tmp, start_ptn, end_ptn, color, 2, cv2.LINE_AA) result_img = cv2.addWeighted(result_img, 0.5, result_img_tmp, 0.5, 0.0) diff --git a/ruff.toml b/ruff.toml index 9f29fb90..40b2f1f8 100644 --- a/ruff.toml +++ b/ruff.toml @@ -15,15 +15,13 @@ select = [ # isort "I", ] -ignore = ["SIM113", "SIM117", "E501", "F401", "F403", - "UP030", "B007", "E402", "E741", "B006", - "B008", "B028", "B904", "UP031", "E722"] +ignore = ["E501", "F401", "F403", "UP030", "B006", "B008"] [lint.per-file-ignores] -"limap/line2d/SOLD2/model/*.py" = ["SIM"] -"limap/line2d/SOLD2/misc/*.py" = ["SIM"] -"limap/line2d/LineTR/*.py" = ["F", "SIM"] +"limap/estimators/absolute_pose/_pl_estimate_absolute_pose.py" = ["F821"] "limap/line2d/L2D2/RAL_net_cov.py" = ["SIM"] -"limap/features/models/s2dnet.py" = ["F", "UP"] -"limap/features/models/vggnet.py" = ["F"] -"limap/estimators/absolute_pose/_pl_estimate_absolute_pose.py" = ["F"] +"limap/line2d/LineTR/*.py" = ["F405", "F841", "SIM"] +"limap/line2d/SOLD2/model/*.py" = ["UP031", "SIM"] +"limap/line2d/SOLD2/misc/*.py" = ["E741", "UP031", "SIM"] +"limap/line2d/SOLD2/train.py" = ["UP031"] +"limap/point2d/superpoint/main.py" = ["B904"] diff --git a/runners/cambridge/utils.py b/runners/cambridge/utils.py index d2d10dea..645e2195 100644 --- a/runners/cambridge/utils.py +++ b/runners/cambridge/utils.py @@ -60,7 +60,7 @@ def read_scene_visualsfm( def get_scene_info(vsfm_path, imagecols, query_images): with open(os.path.join(vsfm_path, "dataset_train.txt")) as f: lines = f.readlines()[3:] - train_names = [l.split()[0] for l in lines] + train_names = [line.split()[0] for line in lines] query_start_idx = 0 if query_images is None: @@ -68,7 +68,7 @@ def get_scene_info(vsfm_path, imagecols, query_images): query_start_idx = 3 with open(query_images) as f: lines = f.readlines()[query_start_idx:] - query_names = [l.split()[0] for l in lines] + query_names = [line.split()[0] for line in lines] train_ids = [] query_ids = [] diff --git a/runners/tests/line2d.py b/runners/tests/line2d.py index 57b5659f..588d0fae 100644 --- a/runners/tests/line2d.py +++ b/runners/tests/line2d.py @@ -1,3 +1,5 @@ +import cv2 + import limap.base import limap.line2d import limap.util.config @@ -23,8 +25,6 @@ desc2 = extractor.extract(view2, segs2) # description # visualize -import cv2 - img1 = view1.read_image(set_gray=False) img1 = limap.visualize.draw_segments(img1, segs1, (0, 255, 0)) cv2.imshow("detections", img1) diff --git a/scripts/tnt_align.py b/scripts/tnt_align.py index 52316818..caca3eae 100644 --- a/scripts/tnt_align.py +++ b/scripts/tnt_align.py @@ -25,12 +25,12 @@ def read_positions(log_file): n_images = int(len(lines) / 5) positions = [] counter = 0 - for img_id in range(n_images): + for _ in range(n_images): counter += 1 mat = [] - for idx in range(4): - l = lines[counter].strip("\n").split(" ") - mat.append([float(k) for k in l]) + for _ in range(4): + line = lines[counter].strip("\n").split(" ") + mat.append([float(k) for k in line]) counter += 1 mat = np.array(mat) pos = mat[:3, 3] @@ -43,8 +43,8 @@ def read_trans(fname): lines = f.readlines() mat = [] for idx in range(4): - l = lines[idx].strip("\n").split(" ") - mat.append([float(k) for k in l]) + line = lines[idx].strip("\n").split(" ") + mat.append([float(k) for k in line]) mat = np.array(mat) assert np.all(mat[3, :] == np.array([0, 0, 0, 1])) return mat[:3, :]