Tensorflow port of a full NetVLAD network

Overview

netvlad_tf

The main intention of this repo is deployment of a full NetVLAD network, which was originally implemented in Matlab, in Python. We provide the weights corresponding to the best model as TensorFlow checkpoint. The repository also contains code that can be used to import other models that were trained in Matlab, as well as tests to make sure that Python produces similar results as Matlab.

We might or might not port the training code to Python/TensorFlow in the future. See GitHub issues.

For your convenience, here is the BibTeX of NetVLAD:

@InProceedings{Arandjelovic16,
  author       = "Arandjelovi\'c, R. and Gronat, P. and Torii, A. and Pajdla, T. and Sivic, J.",
  title        = "{NetVLAD}: {CNN} architecture for weakly supervised place recognition",
  booktitle    = "IEEE Conference on Computer Vision and Pattern Recognition",
  year         = "2016",
}

This TensorFlow port has been written at the Robotics and Perception Group, University of Zurich and ETH Zurich.

Citation

If you use this code in an academic context, please cite the following ICRA'18 publication:

T. Cieslewski, S. Choudhary, D. Scaramuzza: Data-Efficient Decentralized Visual SLAM IEEE International Conference on Robotics and Automation (ICRA), 2018.

Deploying the default model

Download the checkpoint here(1.1 GB). Extract the zip and move its contents to the checkpoints folder of the repo.

Add the python folder to $PYTHONPATH. Alternatively, ROS users can simply clone this repository into the src folder of a catkin workspace.

Python dependencies, which can all be downloaded with pip are:

numpy
tensorflow-gpu

matplotlib (tests only)
opencv-python (tests only)
scipy (model importing only)

The default network can now be deployed as follows:

import cv2
import numpy as np
import tensorflow as tf

import netvlad_tf.net_from_mat as nfm
import netvlad_tf.nets as nets

tf.reset_default_graph()

image_batch = tf.placeholder(
        dtype=tf.float32, shape=[None, None, None, 3])

net_out = nets.vgg16NetvladPca(image_batch)
saver = tf.train.Saver()

sess = tf.Session()
saver.restore(sess, nets.defaultCheckpoint())

inim = cv2.imread(nfm.exampleImgPath())
inim = cv2.cvtColor(inim, cv2.COLOR_BGR2RGB)

batch = np.expand_dims(inim, axis=0)
result = sess.run(net_out, feed_dict={image_batch: batch})

A test to make sure that you get the correct output

To verify that you get the correct output, download this mat (83MB) and put it into the matlab folder. Then, you can run tests/test_nets.py: if it passes, you get the same output as the Matlab implementation for the example image. Note: An issue has been reported where some versions of Matlab and Python load images differently.

Importing other models trained with Matlab

Assuming you have a .mat file with your model:

  1. Run it through matlab/net_class2struct. This converts all serialized classes to serialized structs and is necessary for Python to be able to read all data fields. Note that Matlab needs access to the corresponding class definitions, so you probably need to have NetVLAD set up in Matlab.
  2. Make sure it runs through net_from_mat.netFromMat(). You might need to adapt some of the code there if you use a model that differs from the default one. It is helpful to use the Matlab variable inspector for debugging here.
  3. Adapt and run tests/test_net_from_mat.py. This helps you to ensure that all intermediate layers produce reasonably similar results.
  4. See mat_to_checkpoint.py for how to convert a mat file to a checkpoint. Once you have the checkpoint, you can define the network from scratch (compare to nets.vgg16NetvladPca()). Now, if all variables have been named consistently, you have a pure TensorFlow version of your NetVLAD network model. See tests/test_nets.py for a test that also verifies this implementation.

Performance test on KITTI 00

See matlab/kitti_pr.m and tests/test_kitti.py for further testing which ensures that place recognition performance is consistent between the Matlab and Python implementations. This test requires the grayscale odometry data of KITTI to be linked in the main folder of the repo.

kitti

Comments
  • Output does not correspond

    Output does not correspond

    Hello. First, thanks for your contribution with this repo.

    I downloaded it a couple days ago and I began to try. As you suggest, I ran the matlab scripts in order to get the checkpoint. I am using the vd16_pitts30k_conv5_3_vlad_preL2_intra_white model, so I did not need to make any changes in the scripts. I got my structed.mat and the followed the steps. So, I ran the test_net_from_mat.py script, and the output became this:

    Took 0.059705 seconds
    Layer vgg16_netvlad_pca/:		Max error is 42.000004
    F
    ======================================================================
    FAIL: testNetFromMat (__main__.TestNetFromMat)
    Need example_stats.mat in matlab folder, which can be generated
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "test_net_from_mat.py", line 50, in testNetFromMat
        self.assertLess(maxod, 0.018)
    AssertionError: 42.000004 not less than 0.018
    
    ----------------------------------------------------------------------
    Ran 1 test in 13.200s
    
    FAILED (failures=1)
    

    I also ran the test_nets.py and the output was this:

    Took 0.054931 seconds
    F
    ======================================================================
    FAIL: testVgg16NetvladPca (__main__.TestNets)
    Need example_stats.mat in matlab folder, which can be generated
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "test_nets.py", line 49, in testVgg16NetvladPca
        self.assertLess(np.linalg.norm(out_diff), 0.0053)
    AssertionError: 0.040490005 not less than 0.0053
    
    ----------------------------------------------------------------------
    Ran 1 test in 2.503s
    
    FAILED (failures=1)
    

    I have been comparing the descriptor of some images to the descriptor extracted by the matlab implementation and it is very different. Am I missing something? I have also downloaded the checkpoint given, and the results are the same. It seems like somewhere the implementations are different. I have also tried to run the graph from the .meta file and also from your file. The results are always the same. It seems like there is something in which Tensorflow and Matconvnet differ.

    I have Tensorflow 1.8.0

    Thanks in advance

    opened by AlbertoJaenal 11
  • converting .mat model to struct failed

    converting .mat model to struct failed

    I got an error when converting model trained by Matlab vd16_pitts30k_conv5_3_vlad_preL2_intra_white.mat into struct using matlab/net_class2struct.

    The error says that "Index exceeds matrix dimensions". And I found that the net.layers imported from vd16_pitts30k_conv5_3_vlad_preL2_intra_white.mat had empty members, which caused the error. The same problem occurs in the AlexNet models trained by myself on Matlab.

    How can I solve this problem? Thx.

    opened by chengricky 5
  • convert to pb model file and using libtensorflow to interface

    convert to pb model file and using libtensorflow to interface

    Hi @tcies Thanks for your great works! I want to use your pretrained model in libtensorflow, because I need to use c++ api. I convert your checkpoint files to pb model file using freeze_graph.py scipts, but the pb model can not use in libtensorflow , because I found the pb files only left 1 opts (vgg16_netvlad_pca/WPCA/kernel). my code are as follows:

    def freeze_graph(input_checkpoint,output_graph): output_node_names = "vgg16_netvlad_pca/WPCA/kernel" saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=True)

    with tf.Session() as sess:
        saver.restore(sess, input_checkpoint) 
        output_graph_def = graph_util.convert_variables_to_constants(  
            sess=sess,
            input_graph_def=sess.graph_def,
            output_node_names=output_node_names.split(","))
    
        with tf.gfile.GFile(output_graph, "wb") as f: 
            f.write(output_graph_def.SerializeToString()) 
        print("%d ops in the final graph." % len(output_graph_def.node)) 
    

    if name == "main": input_checkpoint='netvlad/vd16_pitts30k_conv5_3_vlad_preL2_intra_white' out_pb_path="./frozen_model.pb" freeze_graph(input_checkpoint,out_pb_path)

    any suggestions? thanks!

    opened by wolf943134497 0
  • the problem in M2 about Is a directory: perhaps your file is in a different file format and you need to use a different restore operator?

    the problem in M2 about Is a directory: perhaps your file is in a different file format and you need to use a different restore operator?

    My computer is macbook M2,i alredy extract the zip and move its contents to the checkpoints folder of the repo, when i run default network code,the have bug in those: 2022-11-22 20:42:45.803163: W tensorflow/core/util/tensor_slice_reader.cc:96] Could not open /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white: FAILED_PRECONDITION: /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white; Is a directory: perhaps your file is in a different file format and you need to use a different restore operator? 2022-11-22 20:42:45.803195: W tensorflow/core/util/tensor_slice_reader.cc:96] Could not open /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white: FAILED_PRECONDITION: /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white; Is a directory: perhaps your file is in a different file format and you need to use a different restore operator? 2022-11-22 20:42:45.803207: W tensorflow/core/framework/op_kernel.cc:1745] OP_REQUIRES failed at save_restore_tensor.cc:188 : DATA_LOSS: Unable to open table file /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white: FAILED_PRECONDITION: /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white; Is a directory: perhaps your file is in a different file format and you need to use a different restore operator? Traceback (most recent call last): File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/client/session.py", line 1377, in _do_call return fn(*args) File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/client/session.py", line 1360, in _run_fn return self._call_tf_sessionrun(options, feed_dict, fetch_list, File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/client/session.py", line 1453, in _call_tf_sessionrun return tf_session.TF_SessionRun_wrapper(self._session, options, feed_dict, tensorflow.python.framework.errors_impl.DataLossError: 2 root error(s) found. (0) DATA_LOSS: Unable to open table file /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white: FAILED_PRECONDITION: /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white; Is a directory: perhaps your file is in a different file format and you need to use a different restore operator? [[{{node save/RestoreV2}}]] [[GroupCrossDeviceControlEdges_0/save/restore_all/_2]] (1) DATA_LOSS: Unable to open table file /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white: FAILED_PRECONDITION: /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white; Is a directory: perhaps your file is in a different file format and you need to use a different restore operator? [[{{node save/RestoreV2}}]] 0 successful operations. 0 derived errors ignored.

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last): File "/Users/yuqiula/Downloads/netvlad_tf_open-master/python/netvlad_tf/test.py", line 17, in saver.restore(sess, nets.defaultCheckpoint()) File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/training/saver.py", line 1417, in restore sess.run(self.saver_def.restore_op_name, File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/client/session.py", line 967, in run result = self._run(None, fetches, feed_dict, options_ptr, File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/client/session.py", line 1190, in _run results = self._do_run(handle, final_targets, final_fetches, File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/client/session.py", line 1370, in _do_run return self._do_call(_run_fn, feeds, fetches, targets, options, File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/client/session.py", line 1396, in _do_call raise type(e)(node_def, op, message) # pylint: disable=no-value-for-parameter tensorflow.python.framework.errors_impl.DataLossError: Graph execution error:

    Detected at node 'save/RestoreV2' defined at (most recent call last): File "/Users/yuqiula/Downloads/netvlad_tf_open-master/python/netvlad_tf/test.py", line 14, in saver = tf.train.Saver() Node: 'save/RestoreV2' Detected at node 'save/RestoreV2' defined at (most recent call last): File "/Users/yuqiula/Downloads/netvlad_tf_open-master/python/netvlad_tf/test.py", line 14, in saver = tf.train.Saver() Node: 'save/RestoreV2' 2 root error(s) found. (0) DATA_LOSS: Unable to open table file /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white: FAILED_PRECONDITION: /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white; Is a directory: perhaps your file is in a different file format and you need to use a different restore operator? [[{{node save/RestoreV2}}]] [[GroupCrossDeviceControlEdges_0/save/restore_all/_2]] (1) DATA_LOSS: Unable to open table file /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white: FAILED_PRECONDITION: /Users/yuqiula/Downloads/netvlad_tf_open-master/checkpoints/vd16_pitts30k_conv5_3_vlad_preL2_intra_white; Is a directory: perhaps your file is in a different file format and you need to use a different restore operator? [[{{node save/RestoreV2}}]] 0 successful operations. 0 derived errors ignored.

    Original stack trace for 'save/RestoreV2': File "/Users/yuqiula/Downloads/netvlad_tf_open-master/python/netvlad_tf/test.py", line 14, in saver = tf.train.Saver() File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/training/saver.py", line 933, in init self.build() File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/training/saver.py", line 945, in build self._build(self._filename, build_save=True, build_restore=True) File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/training/saver.py", line 973, in _build self.saver_def = self._builder._build_internal( # pylint: disable=protected-access File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/training/saver.py", line 543, in _build_internal restore_op = self._AddRestoreOps(filename_tensor, saveables, File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/training/saver.py", line 363, in _AddRestoreOps all_tensors = self.bulk_restore(filename_tensor, saveables, preferred_shard, File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/training/saver.py", line 611, in bulk_restore return io_ops.restore_v2(filename_tensor, names, slices, dtypes) File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/ops/gen_io_ops.py", line 1501, in restore_v2 _, _, _op, _outputs = _op_def_library._apply_op_helper( File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/framework/op_def_library.py", line 797, in _apply_op_helper op = g._create_op_internal(op_type_name, inputs, dtypes=None, File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/framework/ops.py", line 3754, in _create_op_internal ret = Operation( File "/Users/yuqiula/miniforge3/lib/python3.9/site-packages/tensorflow/python/framework/ops.py", line 2133, in init self._traceback = tf_stack.extract_stack_for_node(self._c_op)

    opened by yuqiulajiao 0
  • Tensorflow version problem

    Tensorflow version problem

    I download the project in my WINDOWS PC. I'm using tensorflow-gpu 2.2.0, but when I try to run the test code, it shows "AttributeError: module 'tensorflow' has no attribute 'reset_default_graph ". I'd like to know the specific thesorflow verison used in the project. Thanks!

    opened by tonglizi 3
  • Convolution Layer Question.

    Convolution Layer Question.

    Thank you for your code at first. I have a question about convolution layer before softmax. I remember that convlution layer should have bias term in original paper. However, the code set bias as None.

    opened by zhilee2019 0
Owner
Robotics and Perception Group
Robotics and Perception Group
Full body anonymization - Realistic Full-Body Anonymization with Surface-Guided GANs

Realistic Full-Body Anonymization with Surface-Guided GANs This is the official

Håkon Hukkelås 30 Nov 18, 2022
TensorFlow ROCm port

Documentation TensorFlow is an end-to-end open source platform for machine learning. It has a comprehensive, flexible ecosystem of tools, libraries, a

ROCm Software Platform 622 Jan 9, 2023
The full training script for Enformer (Tensorflow Sonnet) on TPU clusters

Enformer TPU training script (wip) The full training script for Enformer (Tensorflow Sonnet) on TPU clusters, in an effort to migrate the model to pyt

Phil Wang 10 Oct 19, 2022
[CVPR2021 Oral] FFB6D: A Full Flow Bidirectional Fusion Network for 6D Pose Estimation.

FFB6D This is the official source code for the CVPR2021 Oral work, FFB6D: A Full Flow Biderectional Fusion Network for 6D Pose Estimation. (Arxiv) Tab

Yisheng (Ethan) He 201 Dec 28, 2022
hipCaffe: the HIP port of Caffe

Caffe Caffe is a deep learning framework made with expression, speed, and modularity in mind. It is developed by the Berkeley Vision and Learning Cent

ROCm Software Platform 126 Dec 5, 2022
Pytorch port of Google Research's LEAF Audio paper

leaf-audio-pytorch Pytorch port of Google Research's LEAF Audio paper published at ICLR 2021. This port is not completely finished, but the Leaf() fro

Dennis Fedorishin 80 Oct 31, 2022
A data-driven maritime port simulator

PySeidon - A Data-Driven Maritime Port Simulator ?? Extendable and modular software for maritime port simulation. This software uses entity-component

null 6 Apr 10, 2022
A PyTorch port of the Neural 3D Mesh Renderer

Neural 3D Mesh Renderer (CVPR 2018) This repo contains a PyTorch implementation of the paper Neural 3D Mesh Renderer by Hiroharu Kato, Yoshitaka Ushik

Daniilidis Group University of Pennsylvania 1k Jan 9, 2023
A big endian Gentoo port developed on a Pine64.org RockPro64

Gentoo-aarch64_be A big endian Gentoo port developed on a Pine64.org RockPro64 The endian wars are over... little endian won. As a result, it is incre

Rory Bolt 6 Dec 7, 2022
A port of muP to JAX/Haiku

MUP for Haiku This is a (very preliminary) port of Yang and Hu et al.'s μP repo to Haiku and JAX. It's not feature complete, and I'm very open to sugg

null 18 Dec 30, 2022
Deploy tensorflow graphs for fast evaluation and export to tensorflow-less environments running numpy.

Deploy tensorflow graphs for fast evaluation and export to tensorflow-less environments running numpy. Now with tensorflow 1.0 support. Evaluation usa

Marcel R. 349 Aug 6, 2022
TensorFlow Ranking is a library for Learning-to-Rank (LTR) techniques on the TensorFlow platform

TensorFlow Ranking is a library for Learning-to-Rank (LTR) techniques on the TensorFlow platform

null 2.6k Jan 4, 2023
Robust Video Matting in PyTorch, TensorFlow, TensorFlow.js, ONNX, CoreML!

Robust Video Matting in PyTorch, TensorFlow, TensorFlow.js, ONNX, CoreML!

Peter Lin 6.5k Jan 4, 2023
Robust Video Matting in PyTorch, TensorFlow, TensorFlow.js, ONNX, CoreML!

Robust Video Matting (RVM) English | 中文 Official repository for the paper Robust High-Resolution Video Matting with Temporal Guidance. RVM is specific

flow-dev 2 Aug 21, 2022
TensorFlow-based neural network library

Sonnet Documentation | Examples Sonnet is a library built on top of TensorFlow 2 designed to provide simple, composable abstractions for machine learn

DeepMind 9.5k Jan 7, 2023
TensorFlow code for the neural network presented in the paper: "Structural Language Models of Code" (ICML'2020)

SLM: Structural Language Models of Code This is an official implementation of the model described in: "Structural Language Models of Code" [PDF] To ap

null 73 Nov 6, 2022
High level network definitions with pre-trained weights in TensorFlow

TensorNets High level network definitions with pre-trained weights in TensorFlow (tested with 2.1.0 >= TF >= 1.4.0). Guiding principles Applicability.

Taehoon Lee 1k Dec 13, 2022
Cascaded Pyramid Network (CPN) based on Keras (Tensorflow backend)

ML2 Takehome Project Reimplementing the paper: Cascaded Pyramid Network for Multi-Person Pose Estimation Dataset The model uses the COCO dataset which

Vo Van Tu 1 Nov 22, 2021