Spaces:
Running on Zero
Running on Zero
update: features and matchers
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- third_party/ALIKE/LICENSEAdded+29
- third_party/ALIKE/README.mdAdded+131
- third_party/ALIKE/alike.pyAdded+143
- third_party/ALIKE/alnet.pyAdded+164
- third_party/ALIKE/assets/ALIKE_code.zipAdded+3
- third_party/ALIKE/assets/alike.pngAdded
- third_party/ALIKE/assets/kitti.gifAdded
- third_party/ALIKE/assets/kitti/000100.pngAdded
- third_party/ALIKE/assets/kitti/000101.pngAdded
- third_party/ALIKE/assets/kitti/000102.pngAdded
- third_party/ALIKE/assets/kitti/000103.pngAdded
- third_party/ALIKE/assets/kitti/000104.pngAdded
- third_party/ALIKE/assets/kitti/000105.pngAdded
- third_party/ALIKE/assets/kitti/000106.pngAdded
- third_party/ALIKE/assets/kitti/000107.pngAdded
- third_party/ALIKE/assets/kitti/000108.pngAdded
- third_party/ALIKE/assets/kitti/000109.pngAdded
- third_party/ALIKE/assets/kitti/000110.pngAdded
- third_party/ALIKE/assets/kitti/000111.pngAdded
- third_party/ALIKE/assets/kitti/000112.pngAdded
- third_party/ALIKE/assets/kitti/000113.pngAdded
- third_party/ALIKE/assets/kitti/000114.pngAdded
- third_party/ALIKE/assets/kitti/000115.pngAdded
- third_party/ALIKE/assets/kitti/000116.pngAdded
- third_party/ALIKE/assets/kitti/000117.pngAdded
- third_party/ALIKE/assets/kitti/000118.pngAdded
- third_party/ALIKE/assets/kitti/000119.pngAdded
- third_party/ALIKE/assets/tum.gifAdded
- third_party/ALIKE/assets/tum/1311868169.163498.pngAdded
- third_party/ALIKE/assets/tum/1311868169.263274.pngAdded
- third_party/ALIKE/assets/tum/1311868169.363470.pngAdded
- third_party/ALIKE/assets/tum/1311868169.463229.pngAdded
- third_party/ALIKE/assets/tum/1311868169.563501.pngAdded
- third_party/ALIKE/assets/tum/1311868169.663240.pngAdded
- third_party/ALIKE/assets/tum/1311868169.763417.pngAdded
- third_party/ALIKE/assets/tum/1311868169.863396.pngAdded
- third_party/ALIKE/assets/tum/1311868169.963415.pngAdded
- third_party/ALIKE/assets/tum/1311868170.063469.pngAdded
- third_party/ALIKE/assets/tum/1311868170.163416.pngAdded
- third_party/ALIKE/assets/tum/1311868170.263521.pngAdded
- third_party/ALIKE/assets/tum/1311868170.363400.pngAdded
- third_party/ALIKE/assets/tum/1311868170.463383.pngAdded
- third_party/ALIKE/assets/tum/1311868170.563345.pngAdded
- third_party/ALIKE/assets/tum/1311868170.663430.pngAdded
- third_party/ALIKE/assets/tum/1311868170.763453.pngAdded
- third_party/ALIKE/assets/tum/1311868170.863446.pngAdded
- third_party/ALIKE/assets/tum/1311868170.963440.pngAdded
- third_party/ALIKE/assets/tum/1311868171.063438.pngAdded
- third_party/ALIKE/demo.pyAdded+167
- third_party/ALIKE/hseq/cache/alike-l-ms.npyAdded+3
1234567891011121314151617181920212223242526272829BSD 3-Clause License
Copyright (c) 2022, Zhao XiaomingAll rights reserved.
Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THEIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLEFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIALDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ORSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVERCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USEOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# News
- The [ALIKED](https://github.com/Shiaoming/ALIKED) is released.- The [ALIKE training code](https://github.com/Shiaoming/ALIKE/raw/main/assets/ALIKE_code.zip) is released.
# ALIKE: Accurate and Lightweight Keypoint Detection and Descriptor Extraction
ALIKE applies a differentiable keypoint detection module to detect accurate sub-pixel keypoints. The network can run at 95 frames per second for 640 x 480 images on NVIDIA Titan X (Pascal) GPU and achieve equivalent performance with the state-of-the-arts. ALIKE benefits real-time applications in resource-limited platforms/devices. Technical details are described in [this paper](https://arxiv.org/pdf/2112.02906.pdf).
> ```> Xiaoming Zhao, Xingming Wu, Jinyu Miao, Weihai Chen, Peter C. Y. Chen, Zhengguo Li, "ALIKE: Accurate and Lightweight Keypoint> Detection and Descriptor Extraction," IEEE Transactions on Multimedia, 2022.> ```

If you use ALIKE in an academic work, please cite:
```@article{Zhao2023ALIKED, title = {ALIKED: A Lighter Keypoint and Descriptor Extraction Network via Deformable Transformation}, url = {https://arxiv.org/pdf/2304.03608.pdf}, doi = {10.1109/TIM.2023.3271000}, journal = {IEEE Transactions on Instrumentation & Measurement}, author = {Zhao, Xiaoming and Wu, Xingming and Chen, Weihai and Chen, Peter C. Y. and Xu, Qingsong and Li, Zhengguo}, year = {2023}, volume = {72}, pages = {1-16},}
@article{Zhao2022ALIKE, title = {ALIKE: Accurate and Lightweight Keypoint Detection and Descriptor Extraction}, url = {http://arxiv.org/abs/2112.02906}, doi = {10.1109/TMM.2022.3155927}, journal = {IEEE Transactions on Multimedia}, author = {Zhao, Xiaoming and Wu, Xingming and Miao, Jinyu and Chen, Weihai and Chen, Peter C. Y. and Li, Zhengguo}, month = march, year = {2022},}```
## 1. Prerequisites
The required packages are listed in the `requirements.txt` :
```shellpip install -r requirements.txt```
## 2. Models
The off-the-shelf weights of four variant ALIKE models are provided in `models/` .
## 3. Run demo
```shell$ python demo.py -husage: demo.py [-h] [--model {alike-t,alike-s,alike-n,alike-l}] [--device DEVICE] [--top_k TOP_K] [--scores_th SCORES_TH] [--n_limit N_LIMIT] [--no_display] [--no_sub_pixel] input
ALike Demo.
positional arguments: input Image directory or movie file or "camera0" (for webcam0).
optional arguments: -h, --help show this help message and exit --model {alike-t,alike-s,alike-n,alike-l} The model configuration --device DEVICE Running device (default: cuda). --top_k TOP_K Detect top K keypoints. -1 for threshold based mode, >0 for top K mode. (default: -1) --scores_th SCORES_TH Detector score threshold (default: 0.2). --n_limit N_LIMIT Maximum number of keypoints to be detected (default: 5000). --no_display Do not display images to screen. Useful if running remotely (default: False). --no_sub_pixel Do not detect sub-pixel keypoints (default: False).```
## 4. Examples
### KITTI example```shellpython demo.py assets/kitti ```
### TUM example```shellpython demo.py assets/tum ```
## 5. Efficiency and performance
| Models | Parameters | GFLOPs(640x480) | MHA@3 on Hpatches | mAA(10°) on [IMW2020-test](https://www.cs.ubc.ca/research/image-matching-challenge/2021/leaderboard) (Stereo) ||:---:|:---:|:---:|:-----------------:|:-------------------------------------------------------------------------------------------------------------:|| D2-Net(MS) | 7653KB | 889.40 | 38.33% | 12.27% || LF-Net(MS) | 2642KB | 24.37 | 57.78% | 23.44% || SuperPoint | 1301KB | 26.11 | 70.19% | 28.97% || R2D2(MS) | 484KB | 464.55 | 71.48% | 39.02% || ASLFeat(MS) | 823KB | 77.58 | 73.52% | 33.65% || DISK | 1092KB | 98.97 | 70.56% | 51.22% || ALike-N | 318KB | 7.909 | 75.74% | 47.18% || ALike-L | 653KB | 19.685 | 76.85% | 49.58% |
### Evaluation on Hpatches
- Download [hpatches-sequences-release](https://hpatches.github.io/) and put it into `hseq/hpatches-sequences-release`.- Remove the unreliable sequences as D2-Net.- Run the following command to evaluate the performance: ```shell python hseq/eval.py ```
For more details, please refer to the [paper](https://arxiv.org/abs/2112.02906).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143import loggingimport osimport cv2import torchfrom copy import deepcopyimport torch.nn.functional as Ffrom torchvision.transforms import ToTensorimport math
from alnet import ALNetfrom soft_detect import DKDimport time
configs = { 'alike-t': {'c1': 8, 'c2': 16, 'c3': 32, 'c4': 64, 'dim': 64, 'single_head': True, 'radius': 2, 'model_path': os.path.join(os.path.split(__file__)[0], 'models', 'alike-t.pth')}, 'alike-s': {'c1': 8, 'c2': 16, 'c3': 48, 'c4': 96, 'dim': 96, 'single_head': True, 'radius': 2, 'model_path': os.path.join(os.path.split(__file__)[0], 'models', 'alike-s.pth')}, 'alike-n': {'c1': 16, 'c2': 32, 'c3': 64, 'c4': 128, 'dim': 128, 'single_head': True, 'radius': 2, 'model_path': os.path.join(os.path.split(__file__)[0], 'models', 'alike-n.pth')}, 'alike-l': {'c1': 32, 'c2': 64, 'c3': 128, 'c4': 128, 'dim': 128, 'single_head': False, 'radius': 2, 'model_path': os.path.join(os.path.split(__file__)[0], 'models', 'alike-l.pth')},}
class ALike(ALNet): def __init__(self, # ================================== feature encoder c1: int = 32, c2: int = 64, c3: int = 128, c4: int = 128, dim: int = 128, single_head: bool = False, # ================================== detect parameters radius: int = 2, top_k: int = 500, scores_th: float = 0.5, n_limit: int = 5000, device: str = 'cpu', model_path: str = '' ): super().__init__(c1, c2, c3, c4, dim, single_head) self.radius = radius self.top_k = top_k self.n_limit = n_limit self.scores_th = scores_th self.dkd = DKD(radius=self.radius, top_k=self.top_k, scores_th=self.scores_th, n_limit=self.n_limit) self.device = device
if model_path != '': state_dict = torch.load(model_path, self.device) self.load_state_dict(state_dict) self.to(self.device) self.eval() logging.info(f'Loaded model parameters from {model_path}') logging.info( f"Number of model parameters: {sum(p.numel() for p in self.parameters() if p.requires_grad) / 1e3}KB")
def extract_dense_map(self, image, ret_dict=False): # ==================================================== # check image size, should be integer multiples of 2^5 # if it is not a integer multiples of 2^5, padding zeros device = image.device b, c, h, w = image.shape h_ = math.ceil(h / 32) * 32 if h % 32 != 0 else h w_ = math.ceil(w / 32) * 32 if w % 32 != 0 else w if h_ != h: h_padding = torch.zeros(b, c, h_ - h, w, device=device) image = torch.cat([image, h_padding], dim=2) if w_ != w: w_padding = torch.zeros(b, c, h_, w_ - w, device=device) image = torch.cat([image, w_padding], dim=3) # ====================================================
scores_map, descriptor_map = super().forward(image)
# ==================================================== if h_ != h or w_ != w: descriptor_map = descriptor_map[:, :, :h, :w] scores_map = scores_map[:, :, :h, :w] # Bx1xHxW # ====================================================
# BxCxHxW descriptor_map = torch.nn.functional.normalize(descriptor_map, p=2, dim=1)
if ret_dict: return {'descriptor_map': descriptor_map, 'scores_map': scores_map, } else: return descriptor_map, scores_map
def forward(self, img, image_size_max=99999, sort=False, sub_pixel=False): """ :param img: np.array HxWx3, RGB :param image_size_max: maximum image size, otherwise, the image will be resized :param sort: sort keypoints by scores :param sub_pixel: whether to use sub-pixel accuracy :return: a dictionary with 'keypoints', 'descriptors', 'scores', and 'time' """ H, W, three = img.shape assert three == 3, "input image shape should be [HxWx3]"
# ==================== image size constraint image = deepcopy(img) max_hw = max(H, W) if max_hw > image_size_max: ratio = float(image_size_max / max_hw) image = cv2.resize(image, dsize=None, fx=ratio, fy=ratio)
# ==================== convert image to tensor image = torch.from_numpy(image).to(self.device).to(torch.float32).permute(2, 0, 1)[None] / 255.0
# ==================== extract keypoints start = time.time()
with torch.no_grad(): descriptor_map, scores_map = self.extract_dense_map(image) keypoints, descriptors, scores, _ = self.dkd(scores_map, descriptor_map, sub_pixel=sub_pixel) keypoints, descriptors, scores = keypoints[0], descriptors[0], scores[0] keypoints = (keypoints + 1) / 2 * keypoints.new_tensor([[W - 1, H - 1]])
if sort: indices = torch.argsort(scores, descending=True) keypoints = keypoints[indices] descriptors = descriptors[indices] scores = scores[indices]
end = time.time()
return {'keypoints': keypoints.cpu().numpy(), 'descriptors': descriptors.cpu().numpy(), 'scores': scores.cpu().numpy(), 'scores_map': scores_map.cpu().numpy(), 'time': end - start, }
if __name__ == '__main__': import numpy as np from thop import profile
net = ALike(c1=32, c2=64, c3=128, c4=128, dim=128, single_head=False)
image = np.random.random((640, 480, 3)).astype(np.float32) flops, params = profile(net, inputs=(image, 9999, False), verbose=False) print('{:<30} {:<8} GFLops'.format('Computational complexity: ', flops / 1e9)) print('{:<30} {:<8} KB'.format('Number of parameters: ', params / 1e3))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164import torchfrom torch import nnfrom torchvision.models import resnetfrom typing import Optional, Callable
class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels, gate: Optional[Callable[..., nn.Module]] = None, norm_layer: Optional[Callable[..., nn.Module]] = None): super().__init__() if gate is None: self.gate = nn.ReLU(inplace=True) else: self.gate = gate if norm_layer is None: norm_layer = nn.BatchNorm2d self.conv1 = resnet.conv3x3(in_channels, out_channels) self.bn1 = norm_layer(out_channels) self.conv2 = resnet.conv3x3(out_channels, out_channels) self.bn2 = norm_layer(out_channels)
def forward(self, x): x = self.gate(self.bn1(self.conv1(x))) # B x in_channels x H x W x = self.gate(self.bn2(self.conv2(x))) # B x out_channels x H x W return x
# copied from torchvision\models\resnet.py#27->BasicBlockclass ResBlock(nn.Module): expansion: int = 1
def __init__( self, inplanes: int, planes: int, stride: int = 1, downsample: Optional[nn.Module] = None, groups: int = 1, base_width: int = 64, dilation: int = 1, gate: Optional[Callable[..., nn.Module]] = None, norm_layer: Optional[Callable[..., nn.Module]] = None ) -> None: super(ResBlock, self).__init__() if gate is None: self.gate = nn.ReLU(inplace=True) else: self.gate = gate if norm_layer is None: norm_layer = nn.BatchNorm2d if groups != 1 or base_width != 64: raise ValueError('ResBlock only supports groups=1 and base_width=64') if dilation > 1: raise NotImplementedError("Dilation > 1 not supported in ResBlock") # Both self.conv1 and self.downsample layers downsample the input when stride != 1 self.conv1 = resnet.conv3x3(inplanes, planes, stride) self.bn1 = norm_layer(planes) self.conv2 = resnet.conv3x3(planes, planes) self.bn2 = norm_layer(planes) self.downsample = downsample self.stride = stride
def forward(self, x: torch.Tensor) -> torch.Tensor: identity = x
out = self.conv1(x) out = self.bn1(out) out = self.gate(out)
out = self.conv2(out) out = self.bn2(out)
if self.downsample is not None: identity = self.downsample(x)
out += identity out = self.gate(out)
return out
class ALNet(nn.Module): def __init__(self, c1: int = 32, c2: int = 64, c3: int = 128, c4: int = 128, dim: int = 128, single_head: bool = True, ): super().__init__()
self.gate = nn.ReLU(inplace=True)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2) self.pool4 = nn.MaxPool2d(kernel_size=4, stride=4)
self.block1 = ConvBlock(3, c1, self.gate, nn.BatchNorm2d)
self.block2 = ResBlock(inplanes=c1, planes=c2, stride=1, downsample=nn.Conv2d(c1, c2, 1), gate=self.gate, norm_layer=nn.BatchNorm2d) self.block3 = ResBlock(inplanes=c2, planes=c3, stride=1, downsample=nn.Conv2d(c2, c3, 1), gate=self.gate, norm_layer=nn.BatchNorm2d) self.block4 = ResBlock(inplanes=c3, planes=c4, stride=1, downsample=nn.Conv2d(c3, c4, 1), gate=self.gate, norm_layer=nn.BatchNorm2d)
# ================================== feature aggregation self.conv1 = resnet.conv1x1(c1, dim // 4) self.conv2 = resnet.conv1x1(c2, dim // 4) self.conv3 = resnet.conv1x1(c3, dim // 4) self.conv4 = resnet.conv1x1(dim, dim // 4) self.upsample2 = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) self.upsample4 = nn.Upsample(scale_factor=4, mode='bilinear', align_corners=True) self.upsample8 = nn.Upsample(scale_factor=8, mode='bilinear', align_corners=True) self.upsample32 = nn.Upsample(scale_factor=32, mode='bilinear', align_corners=True)
# ================================== detector and descriptor head self.single_head = single_head if not self.single_head: self.convhead1 = resnet.conv1x1(dim, dim) self.convhead2 = resnet.conv1x1(dim, dim + 1)
def forward(self, image): # ================================== feature encoder x1 = self.block1(image) # B x c1 x H x W x2 = self.pool2(x1) x2 = self.block2(x2) # B x c2 x H/2 x W/2 x3 = self.pool4(x2) x3 = self.block3(x3) # B x c3 x H/8 x W/8 x4 = self.pool4(x3) x4 = self.block4(x4) # B x dim x H/32 x W/32
# ================================== feature aggregation x1 = self.gate(self.conv1(x1)) # B x dim//4 x H x W x2 = self.gate(self.conv2(x2)) # B x dim//4 x H//2 x W//2 x3 = self.gate(self.conv3(x3)) # B x dim//4 x H//8 x W//8 x4 = self.gate(self.conv4(x4)) # B x dim//4 x H//32 x W//32 x2_up = self.upsample2(x2) # B x dim//4 x H x W x3_up = self.upsample8(x3) # B x dim//4 x H x W x4_up = self.upsample32(x4) # B x dim//4 x H x W x1234 = torch.cat([x1, x2_up, x3_up, x4_up], dim=1)
# ================================== detector and descriptor head if not self.single_head: x1234 = self.gate(self.convhead1(x1234)) x = self.convhead2(x1234) # B x dim+1 x H x W
descriptor_map = x[:, :-1, :, :] scores_map = torch.sigmoid(x[:, -1, :, :]).unsqueeze(1)
return scores_map, descriptor_map
if __name__ == '__main__': from thop import profile
net = ALNet(c1=16, c2=32, c3=64, c4=128, dim=128, single_head=True)
image = torch.randn(1, 3, 640, 480) flops, params = profile(net, inputs=(image,), verbose=False) print('{:<30} {:<8} GFLops'.format('Computational complexity: ', flops / 1e9)) print('{:<30} {:<8} KB'.format('Number of parameters: ', params / 1e3))123version https://git-lfs.github.com/spec/v1oid sha256:891e8431c047e7aeed77c9e5f64ffeed262d92389d8ae6235dde0964a9048a08size 62774123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167import copyimport osimport cv2import globimport loggingimport argparseimport numpy as npfrom tqdm import tqdmfrom alike import ALike, configs
class ImageLoader(object): def __init__(self, filepath: str): self.N = 3000 if filepath.startswith('camera'): camera = int(filepath[6:]) self.cap = cv2.VideoCapture(camera) if not self.cap.isOpened(): raise IOError(f"Can't open camera {camera}!") logging.info(f'Opened camera {camera}') self.mode = 'camera' elif os.path.exists(filepath): if os.path.isfile(filepath): self.cap = cv2.VideoCapture(filepath) if not self.cap.isOpened(): raise IOError(f"Can't open video {filepath}!") rate = self.cap.get(cv2.CAP_PROP_FPS) self.N = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1 duration = self.N / rate logging.info(f'Opened video {filepath}') logging.info(f'Frames: {self.N}, FPS: {rate}, Duration: {duration}s') self.mode = 'video' else: self.images = glob.glob(os.path.join(filepath, '*.png')) + \ glob.glob(os.path.join(filepath, '*.jpg')) + \ glob.glob(os.path.join(filepath, '*.ppm')) self.images.sort() self.N = len(self.images) logging.info(f'Loading {self.N} images') self.mode = 'images' else: raise IOError('Error filepath (camerax/path of images/path of videos): ', filepath)
def __getitem__(self, item): if self.mode == 'camera' or self.mode == 'video': if item > self.N: return None ret, img = self.cap.read() if not ret: raise "Can't read image from camera" if self.mode == 'video': self.cap.set(cv2.CAP_PROP_POS_FRAMES, item) elif self.mode == 'images': filename = self.images[item] img = cv2.imread(filename) if img is None: raise Exception('Error reading image %s' % filename) return img
def __len__(self): return self.N
class SimpleTracker(object): def __init__(self): self.pts_prev = None self.desc_prev = None
def update(self, img, pts, desc): N_matches = 0 if self.pts_prev is None: self.pts_prev = pts self.desc_prev = desc
out = copy.deepcopy(img) for pt1 in pts: p1 = (int(round(pt1[0])), int(round(pt1[1]))) cv2.circle(out, p1, 1, (0, 0, 255), -1, lineType=16) else: matches = self.mnn_mather(self.desc_prev, desc) mpts1, mpts2 = self.pts_prev[matches[:, 0]], pts[matches[:, 1]] N_matches = len(matches)
out = copy.deepcopy(img) for pt1, pt2 in zip(mpts1, mpts2): p1 = (int(round(pt1[0])), int(round(pt1[1]))) p2 = (int(round(pt2[0])), int(round(pt2[1]))) cv2.line(out, p1, p2, (0, 255, 0), lineType=16) cv2.circle(out, p2, 1, (0, 0, 255), -1, lineType=16)
self.pts_prev = pts self.desc_prev = desc
return out, N_matches
def mnn_mather(self, desc1, desc2): sim = desc1 @ desc2.transpose() sim[sim < 0.9] = 0 nn12 = np.argmax(sim, axis=1) nn21 = np.argmax(sim, axis=0) ids1 = np.arange(0, sim.shape[0]) mask = (ids1 == nn21[nn12]) matches = np.stack([ids1[mask], nn12[mask]]) return matches.transpose()
if __name__ == '__main__': parser = argparse.ArgumentParser(description='ALike Demo.') parser.add_argument('input', type=str, default='', help='Image directory or movie file or "camera0" (for webcam0).') parser.add_argument('--model', choices=['alike-t', 'alike-s', 'alike-n', 'alike-l'], default="alike-t", help="The model configuration") parser.add_argument('--device', type=str, default='cuda', help="Running device (default: cuda).") parser.add_argument('--top_k', type=int, default=-1, help='Detect top K keypoints. -1 for threshold based mode, >0 for top K mode. (default: -1)') parser.add_argument('--scores_th', type=float, default=0.2, help='Detector score threshold (default: 0.2).') parser.add_argument('--n_limit', type=int, default=5000, help='Maximum number of keypoints to be detected (default: 5000).') parser.add_argument('--no_display', action='store_true', help='Do not display images to screen. Useful if running remotely (default: False).') parser.add_argument('--no_sub_pixel', action='store_true', help='Do not detect sub-pixel keypoints (default: False).') args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
image_loader = ImageLoader(args.input) model = ALike(**configs[args.model], device=args.device, top_k=args.top_k, scores_th=args.scores_th, n_limit=args.n_limit) tracker = SimpleTracker()
if not args.no_display: logging.info("Press 'q' to stop!") cv2.namedWindow(args.model)
runtime = [] progress_bar = tqdm(image_loader) for img in progress_bar: if img is None: break img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) pred = model(img_rgb, sub_pixel=not args.no_sub_pixel) kpts = pred['keypoints'] desc = pred['descriptors'] runtime.append(pred['time'])
out, N_matches = tracker.update(img, kpts, desc)
ave_fps = (1. / np.stack(runtime)).mean() status = f"Fps:{ave_fps:.1f}, Keypoints/Matches: {len(kpts)}/{N_matches}" progress_bar.set_description(status)
if not args.no_display: cv2.setWindowTitle(args.model, args.model + ': ' + status) cv2.imshow(args.model, out) if cv2.waitKey(1) == ord('q'): break
logging.info('Finished!') if not args.no_display: logging.info('Press any key to exit!') cv2.waitKey()123version https://git-lfs.github.com/spec/v1oid sha256:1350ab826afdd9b7542a556e2fda9ad9f94388a875c8edb7874e4bcdfebc63casize 13124third_party/ALIKE/LICENSEAdded+29
third_party/ALIKE/README.mdAdded+131
third_party/ALIKE/alike.pyAdded+143
third_party/ALIKE/alnet.pyAdded+164
third_party/ALIKE/assets/ALIKE_code.zipAdded+3
third_party/ALIKE/assets/alike.pngAdded

Large File Pointer Details
- SHA256: d35e59f8e4d9c34b0e2686ecd5ca5414fe975b81553e4968eccc4bff1535c2d4
- Pointer size: 131 Bytes
- Size of remote file: 162 kB
third_party/ALIKE/assets/kitti.gifAdded

Large File Pointer Details
- SHA256: 0b05e4dc0000b9abf53183a3ebdfc0b95a92513952e235ea24f27f2945389ea1
- Pointer size: 132 Bytes
- Size of remote file: 7.03 MB
third_party/ALIKE/assets/kitti/000100.pngAdded

Large File Pointer Details
- SHA256: c8d4a81ad91c7945cabd15de286aacf27ab661163b5eee0177128721782d5405
- Pointer size: 131 Bytes
- Size of remote file: 273 kB
third_party/ALIKE/assets/kitti/000101.pngAdded

Large File Pointer Details
- SHA256: 539c684432726e903191a2471c8dae8c4b0012b88e1b3af7590de08c24890327
- Pointer size: 131 Bytes
- Size of remote file: 272 kB
third_party/ALIKE/assets/kitti/000102.pngAdded

Large File Pointer Details
- SHA256: 5bbc9a5b04bd425a5e146f3ba114027041086477a5fa123a50463932ab62617e
- Pointer size: 131 Bytes
- Size of remote file: 270 kB
third_party/ALIKE/assets/kitti/000103.pngAdded

Large File Pointer Details
- SHA256: 2041e633aeb85022b1222277cace17132bed09ca19856d1e6787984b05d61339
- Pointer size: 131 Bytes
- Size of remote file: 271 kB
third_party/ALIKE/assets/kitti/000104.pngAdded

Large File Pointer Details
- SHA256: 6ca8a30c0edb7d2c6d6e5c2f5317bdffdae2269157d69e71f9602e0bbf2090ab
- Pointer size: 131 Bytes
- Size of remote file: 271 kB
third_party/ALIKE/assets/kitti/000105.pngAdded

Large File Pointer Details
- SHA256: b8bca67672e8b2181b193f0577a9a3b42b64df9bb57d98608dbdbb54e79925bd
- Pointer size: 131 Bytes
- Size of remote file: 270 kB
third_party/ALIKE/assets/kitti/000106.pngAdded

Large File Pointer Details
- SHA256: 2ccc83d57703afdcda4afd746dd99458b425fbc11ce3155583abde25e988e389
- Pointer size: 131 Bytes
- Size of remote file: 269 kB
third_party/ALIKE/assets/kitti/000107.pngAdded

Large File Pointer Details
- SHA256: 980f4c74ac9117020f954cc75718cf0a09baeb30894aea123db59f9e4555ecef
- Pointer size: 131 Bytes
- Size of remote file: 269 kB
third_party/ALIKE/assets/kitti/000108.pngAdded

Large File Pointer Details
- SHA256: c7c2234c8ba8c056c452a0d625db6eac09c8963b0c5e8a5d0b1c3af15a4b7516
- Pointer size: 131 Bytes
- Size of remote file: 271 kB
third_party/ALIKE/assets/kitti/000109.pngAdded

Large File Pointer Details
- SHA256: 6a34b9639806e7deefe1cb24ae7b376343d394d2d032f95e763e4b6921cd61c7
- Pointer size: 131 Bytes
- Size of remote file: 276 kB
third_party/ALIKE/assets/kitti/000110.pngAdded

Large File Pointer Details
- SHA256: 6af1b3e55b9c1eac208c887c44592f93e8ae7cc0196acaa2639c265f8bf959e3
- Pointer size: 131 Bytes
- Size of remote file: 275 kB
third_party/ALIKE/assets/kitti/000111.pngAdded

Large File Pointer Details
- SHA256: 215ed5306f4976458110836a620dcf55030d8dd20618e6365d60176988c1cfa6
- Pointer size: 131 Bytes
- Size of remote file: 276 kB
third_party/ALIKE/assets/kitti/000112.pngAdded

Large File Pointer Details
- SHA256: 8a265252457871d4dd2f17c42eafa1c0da99df90d103c653c8097aad26073d22
- Pointer size: 131 Bytes
- Size of remote file: 276 kB
third_party/ALIKE/assets/kitti/000113.pngAdded

Large File Pointer Details
- SHA256: c83f220b29b5d04ead44c9304f9eccde3a4ff4e60627d7014f8fe424afb873f4
- Pointer size: 131 Bytes
- Size of remote file: 276 kB
third_party/ALIKE/assets/kitti/000114.pngAdded

Large File Pointer Details
- SHA256: 1abad021db35c21f2e9ac0ce7e54a5721eec3ff32bc4ce820f5b7091af4d6fac
- Pointer size: 131 Bytes
- Size of remote file: 276 kB
third_party/ALIKE/assets/kitti/000115.pngAdded

Large File Pointer Details
- SHA256: 6be815b2b0aa8aa3dc47e314ed6645eeb474996e9a920fab2abe8a35fb3ea089
- Pointer size: 131 Bytes
- Size of remote file: 274 kB
third_party/ALIKE/assets/kitti/000116.pngAdded

Large File Pointer Details
- SHA256: 96b8df04ee570d877a04e43f1f4c30abc7e7383b24ce70a1a83a82dcbd863293
- Pointer size: 131 Bytes
- Size of remote file: 271 kB
third_party/ALIKE/assets/kitti/000117.pngAdded

Large File Pointer Details
- SHA256: f32567394c096442df0c768822af1e21f2163f373eec94b7a36f2941ae08b199
- Pointer size: 131 Bytes
- Size of remote file: 267 kB
third_party/ALIKE/assets/kitti/000118.pngAdded

Large File Pointer Details
- SHA256: b76476a8856d33960302b29cbd339c8bc513c52e7b81b21ba7d9f07dd0e4b096
- Pointer size: 131 Bytes
- Size of remote file: 268 kB
third_party/ALIKE/assets/kitti/000119.pngAdded

Large File Pointer Details
- SHA256: c818d19b8a1ce7051b006361bc14f638d8df2989b0bba8a96472e8551e02e5d1
- Pointer size: 131 Bytes
- Size of remote file: 270 kB
third_party/ALIKE/assets/tum.gifAdded

Large File Pointer Details
- SHA256: df6ecf9666386bfa5925c8e57d196f15c077d550eb84dd392f5f49b90e86a5dc
- Pointer size: 132 Bytes
- Size of remote file: 4.04 MB
third_party/ALIKE/assets/tum/1311868169.163498.pngAdded

Large File Pointer Details
- SHA256: 20bc06c1249727c16efc812082454bc8305438f756bcc95f913b9f79819f08e3
- Pointer size: 131 Bytes
- Size of remote file: 512 kB
third_party/ALIKE/assets/tum/1311868169.263274.pngAdded

Large File Pointer Details
- SHA256: 0954d005c8f9ab146718f52601136c513b96a4414b0a0cbc02a01184686fb01e
- Pointer size: 131 Bytes
- Size of remote file: 516 kB
third_party/ALIKE/assets/tum/1311868169.363470.pngAdded

Large File Pointer Details
- SHA256: 1d2681bb2b8a907d53469d9e67f6d1809b9ec435ec210622bf255c66c8918efd
- Pointer size: 131 Bytes
- Size of remote file: 506 kB
third_party/ALIKE/assets/tum/1311868169.463229.pngAdded

Large File Pointer Details
- SHA256: ba2cd89601523665d0bee9dd3ea2117d9249e7ea4c7b43753298c1bab74cd532
- Pointer size: 131 Bytes
- Size of remote file: 509 kB
third_party/ALIKE/assets/tum/1311868169.563501.pngAdded

Large File Pointer Details
- SHA256: 0a0239c7cb08fefbe4f5ec87f1c5e5fd5a32be11349744dc45158caa7d403744
- Pointer size: 131 Bytes
- Size of remote file: 526 kB
third_party/ALIKE/assets/tum/1311868169.663240.pngAdded

Large File Pointer Details
- SHA256: 6e538c9dbaf4242072949920b3105ccdcfac68af955d623a701b9eea0e6e0f6f
- Pointer size: 131 Bytes
- Size of remote file: 521 kB
third_party/ALIKE/assets/tum/1311868169.763417.pngAdded

Large File Pointer Details
- SHA256: 22a4fadfc031c36efd4cee5f70d0b501557bf820fa4b39a1c77f4268d0c12e86
- Pointer size: 131 Bytes
- Size of remote file: 544 kB
third_party/ALIKE/assets/tum/1311868169.863396.pngAdded

Large File Pointer Details
- SHA256: eae0ee5be82b14aa1ed19e0b20a72bc37964c64732c7016739a5b30158453049
- Pointer size: 131 Bytes
- Size of remote file: 549 kB
third_party/ALIKE/assets/tum/1311868169.963415.pngAdded

Large File Pointer Details
- SHA256: a590b6fdb98c4a4ee8e13aafcd9d2392c78a7881b4cc7fd1109231adc3cc8b91
- Pointer size: 131 Bytes
- Size of remote file: 541 kB
third_party/ALIKE/assets/tum/1311868170.063469.pngAdded

Large File Pointer Details
- SHA256: 3d2d6058e036b307efa7d6008a02103b9c31ed8d0edd4b2f1e9ad49717b89684
- Pointer size: 131 Bytes
- Size of remote file: 550 kB
third_party/ALIKE/assets/tum/1311868170.163416.pngAdded

Large File Pointer Details
- SHA256: 741d1e0ede775dd4b7054314c1a95ed3e5116792245b9eb1a5e2492ffe4d935c
- Pointer size: 131 Bytes
- Size of remote file: 550 kB
third_party/ALIKE/assets/tum/1311868170.263521.pngAdded

Large File Pointer Details
- SHA256: 04ce12ed16c6fa89a9fdb3b64e7471335d13b82b84c7a554b3f9fd08f6e254a0
- Pointer size: 131 Bytes
- Size of remote file: 546 kB
third_party/ALIKE/assets/tum/1311868170.363400.pngAdded

Large File Pointer Details
- SHA256: fb6be184df6fd2ca2e287bc64ada937ce2cec3f5d90e15c244fffa8aa44b11b1
- Pointer size: 131 Bytes
- Size of remote file: 545 kB
third_party/ALIKE/assets/tum/1311868170.463383.pngAdded

Large File Pointer Details
- SHA256: d82953d4580894111f15a5b57e0059dca0baf02e788e0726a2849647cf570b63
- Pointer size: 131 Bytes
- Size of remote file: 542 kB
third_party/ALIKE/assets/tum/1311868170.563345.pngAdded

Large File Pointer Details
- SHA256: d498847d7b8bc2389550941b01e95b1bf6459c70ff645d9893637d59e129ae29
- Pointer size: 131 Bytes
- Size of remote file: 549 kB
third_party/ALIKE/assets/tum/1311868170.663430.pngAdded

Large File Pointer Details
- SHA256: b299c55e430afecb9f5d0ff6e1485ce72d90f5ddf1ec1a186fbcb2b110e035f2
- Pointer size: 131 Bytes
- Size of remote file: 541 kB
third_party/ALIKE/assets/tum/1311868170.763453.pngAdded

Large File Pointer Details
- SHA256: 8073cc59711d6bea5038b698fb74eaa72eeca663dcc35850e0b334e234605385
- Pointer size: 131 Bytes
- Size of remote file: 541 kB
third_party/ALIKE/assets/tum/1311868170.863446.pngAdded

Large File Pointer Details
- SHA256: 70b27a2d1c9e30ad0b164af13eb992b9c54c11aa7b408221515b6b106de87763
- Pointer size: 131 Bytes
- Size of remote file: 544 kB
third_party/ALIKE/assets/tum/1311868170.963440.pngAdded

Large File Pointer Details
- SHA256: 36c02db5125b37725ce2c6fb502ba80e3ff85755dabf1a21d952e186480b8e56
- Pointer size: 131 Bytes
- Size of remote file: 535 kB
third_party/ALIKE/assets/tum/1311868171.063438.pngAdded

Large File Pointer Details
- SHA256: f54d76a6b4bb8d3fb81c257920ddffdf75480bba34d506b481ee6dfaff894ecf
- Pointer size: 131 Bytes
- Size of remote file: 536 kB
third_party/ALIKE/demo.pyAdded+167
third_party/ALIKE/hseq/cache/alike-l-ms.npyAdded+3