Giter Club home page Giter Club logo

netvlad_tf_open's Introduction

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

netvlad_tf_open's People

Contributors

tcies avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

netvlad_tf_open's Issues

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

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.

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.

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)

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!

kitti_pr.mat

Can you provide a trained kitti_pr.mat file with a corresponding link? @tcies Thanks a lot!

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!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.